[英]What's the best way to convert non-generic collection to a generic collection?
[英]Best way to convert a non-generic collection to generic collection
将非泛型集合转换为泛型集合的最佳方法是什么? LINQ有办法吗?
我有以下代码。
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实例,因此请使用LINQ Cast <T>方法 :
public static List<TestClass> ConvertToGenericClass(NonGenericCollection collection)
{
return collection.Cast<TestClass>().ToList();
}
编辑:如果您只想要(可能)异构集合的TestClass实例,请使用OfType <T>过滤它:
public static List<TestClass> ConvertToGenericClass(NonGenericCollection collection)
{
return collection.OfType<TestClass>().ToList();
}
另一种优雅的方法是创建一个这样的包装类(我在我的实用程序项目中包含它)。
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;
}
}
}
你现在可以这样做:
IEnumerable<MyClass> genericized =
new EnumerableGenericizer<MyClass>(nonGenericCollection);
然后,您可以围绕通用集合包装正常的通用列表。
也许不是最好的方法,但它应该有效。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.