C#Lambda根据另一个列表中的存在过滤列表

时间:2014-02-19 03:57:24

标签: c# lambda

列出A :3,5,5,5,7,9
列表B :3,5

两个列表都是相同的类型,这些值来自字段ID。我的目标是构建一个将返回7,9的forloop,因为列表B 中不存在7,9

我尝试过以下但没有运气:

int counter = 0;
foreach(var item in ListA.Where(x=>ListB.Any(b=>x.ID != b.ID)))
{
    counter++;
    //Here I should perform operation with item that having ID 7 and 9
}

更新
在上述情况下使用except方法,counter仍会返回4,因为 ListA 中的每个5都是不同的对象eventhou他们共享相同的ID。我的最终目标是让counter2,无论对象是否相同。只要 ListA 中的ID对象为35,我就会将其排除。

6 个答案:

答案 0 :(得分:4)

只需使用Except扩展方法

即可
foreach (var item in ListA.Except(ListB)) {
  ...
}

答案 1 :(得分:2)

它应该是“ALL”或“Not Any”

foreach(var item in ListA.Where(x=>ListB.All(b=>x.ID != b.ID)))
{
    //Here I should perform operation with item that having ID 7 and 9
}

更新

由于你实际上希望得到除A以外的A的不同结果,所以你可以这样做:

foreach(var item in ListA.GroupBy(m=>m.ID).Where(x=>ListB.All(b=>b.ID != x.Key)))
{
    counter ++;
    Debug.writeline(item.Key);
}

foreach(var id in ListA.Select(x=>x.ID).Distinct().Except(ListB.Select(y=>y.ID)))
{
    counter++;
}

注意:所有未经测试的 - 我暂时没有编译器。

答案 2 :(得分:2)

更改您的查询:

foreach(var item in ListA.Where(x=> !ListB.Any(b => x.ID == b.ID)))

它应该可以正常工作。

答案 3 :(得分:1)

试试这个:

List<int> listA=new List<int>(new[]{ 3,5,7,9});
List<int> listB=new List<int>(new[]{ 3,5});

var items=(from a in listA
           select a).Except(from b in listB
           select b);

foreach(var item in items)
{
    Console.WriteLine(ll);
}

输出

7  
9

答案 4 :(得分:1)

当两个List属于同一类型时,可以使用方法。 如果类型不同。我们可以这样使用。

var outPut = _employees.Where(i =&gt; _employeeExtensions.Any(j =&gt; i.EmpId == j.EmpId));

答案 5 :(得分:0)

我认为您希望将列表中的项目ID设置为不同:

我在LinqPad中放在一起的例子:

void Main()
{
    List<Person> a = new List<Person>()
    {
        new Person { ID = 1 },
        new Person { ID = 2 },
        new Person { ID = 3 },
    };

    List<Person> b = new List<Person>()
    {
        new Person { ID = 1 },
    };

    var c = a.Where(x => b.Any(bprime => bprime.ID != x.ID));

    foreach(var item in c)
    {
        Console.WriteLine(item.ID);
    }
}

class Person
{
    public int ID { get; set; }
}

输出:

2

3

这类似于Except方法,但这将检查元素的属性。

相关问题