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

后端 未结 2 1703
名媛妹妹
名媛妹妹 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 00:58

    Another elegant way is to create a wrapper class like this (I include this in my utilities project).

    public class EnumerableGenericizer<T> : IEnumerable<T>
    {
        public IEnumerable Target { get; set; }
    
        public EnumerableGenericizer(IEnumerable target)
        {
            Target = target;
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    
        public IEnumerator<T> GetEnumerator()
        {
            foreach(T item in Target)
            {
                yield return item;
            }
        }
    }
    

    You can now do this:

    IEnumerable<MyClass> genericized = 
        new EnumerableGenericizer<MyClass>(nonGenericCollection);
    

    You could then wrap a normal generic list around the genericized collection.

    0 讨论(0)
  • 2021-02-20 01:13

    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();
    }
    
    0 讨论(0)
提交回复
热议问题