Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to convert a non-generic collection to generic collection

What is the best way to convert a non-generic collection to a generic collection? Is there a way to LINQ it?

I have the following code.

public class NonGenericCollection:CollectionBase
{
    public void Add(TestClass a)
    {
        List.Add(a);
    }
}

public class ConvertTest
{
    public static List<TestClass> ConvertToGenericClass( NonGenericCollection    collection)
    {
        // Ask for help here.
    }
}

Thanks!

like image 465
J.W. Avatar asked Apr 08 '09 21:04

J.W.


1 Answers

Since you can guarantee they're all TestClass instances, use the LINQ Cast<T> method:

public static List<TestClass> ConvertToGenericClass(NonGenericCollection collection)
{
   return collection.Cast<TestClass>().ToList();
}

Edit: And if you just wanted the TestClass instances of a (possibly) heterogeneous collection, filter it with OfType<T>:

public static List<TestClass> ConvertToGenericClass(NonGenericCollection collection)
{
   return collection.OfType<TestClass>().ToList();
}
like image 85
Mark Brackett Avatar answered Oct 22 '22 23:10

Mark Brackett