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

和自甴很熟 提交于 2019-12-21 07:36:28

问题


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!


回答1:


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



回答2:


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.




回答3:


Maybe not the best way, but it should work.

public class ConvertTest
{
    public static List<TestClass> ConvertToGenericClass( NonGenericCollection    collection) throws I
    {
       List<TestClass> newList = new ArrayList<TestClass>
         for (Object object : collection){
             if(object instanceof TestClass){
                newList.add(object)
              } else {
                throw new IllegalArgumentException();  
              }
          }
     return newList;
    }
}


来源:https://stackoverflow.com/questions/731831/best-way-to-convert-a-non-generic-collection-to-generic-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!