将非通用集合转换为通用集合的最佳方法 [英] Best way to convert a non-generic collection to generic collection

查看:85
本文介绍了将非通用集合转换为通用集合的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将非通用集合转换为通用集合的最佳方法是什么?有没有办法使用LINQ?

What is the best way to convert a non-generic collection to a generic collection? Is there a way to LINQ it?

我有以下代码.

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.
    }
}

谢谢!

推荐答案

由于可以保证它们都是TestClass实例,因此请使用

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

并且,如果您只想要(可能)异构集合的TestClass实例,请使用OfType< T>对其进行过滤:

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

这篇关于将非通用集合转换为通用集合的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆