您是否考虑过使用 LINQ 的OfType扩展方法?它包装一个可枚举并过滤元素,以便只返回指定类型的元素。你可以像这样使用它:
list.AddRange(superList.OfType(Of SubClass)())
甚至:
list = superList.OfType(Of SubClass)().ToList()
抱歉,如果我的语法关闭,我已经有一段时间没有使用 VB.NET
编辑:示例,如承诺:
namespace Demo.ListFilter
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
class Program
{
private class SuperClass
{
}
private class SubClassA :
SuperClass
{
}
private class SubClassB :
SuperClass
{
}
static void Main(string[] args)
{
var superList = new List<SuperClass>()
{
new SuperClass(),
new SuperClass(),
new SuperClass(),
new SuperClass(),
new SubClassA(),
new SubClassA(),
new SubClassA(),
new SubClassB(),
new SubClassB(),
new SubClassB(),
new SubClassB()
};
var listA = new List<SubClassA>();
var listB = new List<SubClassB>();
SplitList(superList, listA, listB);
Console.WriteLine("List A: {0}", listA.Count);
Console.WriteLine("List B: {0}", listB.Count);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
static void SplitList(IList superList, params IList[] subLists)
{
foreach(var subList in subLists)
{
var type = subList.GetType().GetGenericArguments()[0];
FilterList(superList, subList, type);
}
}
static void FilterList(IList superList, IList subList, Type type)
{
var ofTypeMethod = typeof(Enumerable).GetMethod("OfType");
var genericMethod = ofTypeMethod.MakeGenericMethod(type);
var enumerable = (IEnumerable)genericMethod.Invoke(null, new[] { superList });
foreach(var item in enumerable)
{
subList.Add(item);
}
}
}
}
另一个编辑:您还可以组合这样的方法:
static void SplitList(IList superList, params IList[] subLists)
{
var ofTypeMethod = typeof(Enumerable).GetMethod("OfType");
foreach(var subList in subLists)
{
var subListType = subList.GetType();
var type = subListType.GetGenericArguments()[0];
var genericOfTypeMethod = ofTypeMethod.MakeGenericMethod(type);
var enumerable = genericOfTypeMethod.Invoke(null, new[] { superList });
var addRangeMethod = subListType.GetMethod("AddRange");
addRangeMethod.Invoke(subList, new[] { enumerable });
}
}
不要忘记添加错误处理!