简体   繁体   English

LINQ - 在一个列表中查找不在另一个列表中的所有项目

[英]LINQ - Find all items in one list that aren't in another list

I'm stuck with a LINQ query (or any other efficient means of accomplishing the same thing).我坚持使用 LINQ 查询(或任何其他有效的方法来完成同样的事情)。 Can someone show me how I can select all the items in one list that are not present in another list?有人可以告诉我如何选择一个列表中不存在于另一个列表中的所有项目吗?

Basically, I have a list I formed by matching items between two other lists.基本上,我有一个通过在其他两个列表之间匹配项目而形成的列表。 I need to find all the items in the first list that matches weren't found for.我需要找到第一个列表中没有找到匹配项的所有项目。 Can someone fill in the stars in the second LINQ query below with the query that would achieve this goal?有人可以在下面的第二个 LINQ 查询中用可以实现此目标的查询填充星星吗? If I were using TSQL, I would do SELECT * NOT IN () , but I don't think LINQ allows that.如果我使用 TSQL,我会做SELECT * NOT IN () ,但我认为 LINQ 不允许这样做。

//Create some sample lists.
List<IdentifierLookupData> list1 = new List<IdentifierLookupData> { /*Init */ };
List<IdentifierLookupData> list2 = new List<IdentifierLookupData> { /*Init */ };

//Find all items in list1 and list2 that match and store them in joinItems.
var joinItems = (from d1 in list1
    join d2 in list2 on d1 equals d2
    select d1).ToList<IdentiferLookupData>();

//Find all items in list1 not in joinItems.
var deletedItems = (from d1 in list1
     ***select all items not found in joinItems list.***

Try using .Except extension method (docs) :尝试使用.Except扩展方法 (文档)

var result = list1.Except(list2);

will give you all items in list1 that are not in list2 .将为您提供list1中不在list2所有项目。

IMPORTANT: Even though there's a link provided to MSDN docs for the method, I'll point this out here: Except only works out of the box for collections of primitive types, for POCOs/objects you need to implement IEquatable on that object.重要提示:尽管为该方法提供了指向 MSDN 文档的链接,但我会在此处指出这一点: Except开箱即用的原始类型集合,对于 POCO/对象,您需要在该对象上实现 IEquatable。

试试这个:

var List2 = OriginalList.Where(item => !List1.Any(item2 => item2.ID == item.ID));

The easiest way is to use the Except method.最简单的方法是使用Except方法。

var deletedItems = list1.Except(joinItems);

This will return the set of items in list1 that's not contained in joinItems这将返回list1中未包含在joinItems的项目集

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM