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

后端 未结 2 1124
没有蜡笔的小新
没有蜡笔的小新 2021-02-20 00:37

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 NonG         


        
2条回答
  •  余生分开走
    2021-02-20 01:13

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

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

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

    public static List ConvertToGenericClass(NonGenericCollection collection)
    {
       return collection.OfType().ToList();
    }
    

提交回复
热议问题