使用LINQ提取特定类型的List元素

时间:2013-02-26 18:23:33

标签: c# linq list extract

我有一个对象列表,我必须编写一个方法,根据输入参数提取一些元素,这是一个Type数组。该函数必须从列表中返回一个元素数组,每个元素都是类型数组中一个元素的实例。同时,必须从容器列表中删除这些元素,但前提是它们全部存在于列表中。类型比较是通过Type.IsInstanceOfType(o)方法实现的。

class A {}
class B : A {}
class C : A {}
class D : A {}

public static A[] ExtractElements (List<A> list, Type[] specifiers) {...}

Type[] specifiers1 = new Type[2] {typeof(D), typeof(B)};
Type[] specifiers2 = new Type[3] {typeof(C), typeof(A), typeof(D)};
Type[] specifiers3 = new Type[2] {typeof(A), typeof(A)};
Type[] specifiers4 = new Type[2] {typeof(C), typeof(C)};

List<A> list = new List<A> {new B(), new A(), new D(), new C(), new A()};
A[] result1 = ExtractElements (list, specifiers1);

list  = new List<A> {new B(), new A(), new D(), new C(), new A()};
A[] result2 = ExtractElements (list, specifiers2);

list  = new List<A> {new B(), new A(), new D(), new C(), new A()};
A[] result3 = ExtractElements (list, specifiers3);

list  = new List<A> {new B(), new A(), new D(), new C(), new A()};
A[] result4 = ExtractElements (list, specifiers4);

此代码片段的结果将是:

  result1 is {D, B}, list is {A, C, A}  
  result2 is {C, B, D}, list is {A, A}  
  result3 is {B, A}, list is {D, C, A}  
  result4 is empty array, list is {B, A, D, C, A}  

作为单独的努力,可以编写一个类似的ExtractElements方法,如果列表包含请求类型的项目,它们只返回非空数组,列表中的顺序对应于类型输入数组中的元素顺序,如以下

Type[] specifiers5 = new Type[2] {typeof(B), typeof(D)};
Type[] specifiers6 = new Type[2] {typeof(C), typeof(B)};

List<A> list = new List<A> {new B(), new A(), new D(), new C(), new A()};
A[] result5 = ExtractElements (list, specifiers5);

list  = new List<A> {new B(), new A(), new D(), new C(), new A()};
A[] result6 = ExtractElements (list, specifiers6);

此代码片段的结果将是:

result5 is {B, D}, list is {A, C, A}  
result6 is empty array, list is {B, A, D, C, A}  

我知道LINQ是实现此目的的方法,但遗憾的是我没有相关经验。

3 个答案:

答案 0 :(得分:1)

怎么样:

public IEnumerable<TType> ExtractElements<TType>(IEnumerable<TType> list, IEnumerable<Type> specifiers) {
   var specifiersList = specifiers.ToList();

   return list.Where(t => specifiersList.Any(s => s.IsAssignableFrom(t.GetType())));
}

var specifiers5 = new[] {typeof(B), typeof(D)};
var list = new List<A> {new B(), new A(), new D(), new C(), new A()};

// you can call ToArray() if you want but ForEach won't be available on that
// and you'll need a standard foreach() loop
var result5 = ExtractElements(list, specifiers5).ToList();

result5.ForEach(Console.WriteLine);

Type.IsAssignableFrom()上的more information

答案 1 :(得分:0)

这听起来非常适合Enumerable.OfType<T>()

答案 2 :(得分:0)

这应该可以为您提供所需的一切。我在ExtractElements方法中添加了一个可选参数,允许您启用/禁用订单匹配。

public static A[] ExtractElements (List<A> list, Type[] specifiers, bool orderMatters = false)
{
    var allFound = true;
    var listBackup = list.ToList(); // Make a backup copy   
    var returnList = new List<A>();
    var earliestMatch = 0;

    foreach (var spec in specifiers)
    {
        var item = list.FirstOrDefault (i => spec.IsAssignableFrom(i.GetType()));
        if (item != null)
        {
            var matchPosition = list.IndexOf(item);
            if (orderMatters && matchPosition < earliestMatch)  // we have an out of order match
            {
                allFound = false;
                break;
            }
            earliestMatch = matchPosition;
            list.Remove(item);
            returnList.Add(item);
        }
        else
        {
            allFound = false;
            break;
        }
    }

    if(!allFound)
    {
        // Can't just assign list to listBackup because we have to update the 
        // underlying values not the reference that was passed to the function.
        list.Clear();
        listBackup.ForEach(i => list.Add(i));
        returnList.Clear();
    }

    return returnList.ToArray();
}

我建议您抓取LinqPad的副本,以帮助您测试所有LINQ语句并一般了解LINQ

希望这有帮助。