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

后端 未结 2 1107
没有蜡笔的小新
没有蜡笔的小新 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:11

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

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

    You can now do this:

    IEnumerable genericized = 
        new EnumerableGenericizer(nonGenericCollection);
    

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

提交回复
热议问题