C# – How to convert a non-Generic IList to IList

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?

Best Solution

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;