Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a non-Generic IList to IList<T>?

Tags:

c#

I have class that wants an IList<T>, but I have a Systems.Collection.IList, coming from an NHibernate quere.

I want to create a method that converts it to an IList<T>. How do I do this?

like image 617
Malcolm Avatar asked Apr 22 '09 09:04

Malcolm


People also ask

How do I convert IEnumerable to IList?

Convert the IEnumerable<T> instance to a new object which is convertible to IList . For example, in 3.5+ you can call the . ToList() extension method to create a new List<T> over the enumeration.

What is IList t in c#?

The IList<T> generic interface is a descendant of the ICollection<T> generic interface and is the base interface of all generic lists.

Which interface represents a collection of the object that can be individually accessed by index?

IList Interface (System.


1 Answers

If you're sure that all of the elements inherit from T (or whatever type you're using)

IList<T> myList = nonGenericList.Cast<T>().ToList(); 

If you're not sure:

IList<T> myList = nonGenericList.OfType<T>().ToList(); 

Of course, you will need the System.Linq namespace:

using System.Linq; 
like image 117
Tamas Czinege Avatar answered Oct 03 '22 04:10

Tamas Czinege