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

后端 未结 2 1687
名媛妹妹
名媛妹妹 2021-02-20 00:45

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();
    }
    

提交回复
热议问题