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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11418942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:48:28  来源:igfitidea点击:

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

c#.netlinq.net-3.5

提问by John Humphreys - w00te

I'm stuck with a LINQ query (or any other efficient means of accomplishing the same thing). Can someone show me how I can select all the items in one list that are not present in another list?

我坚持使用 LINQ 查询(或任何其他有效的方法来完成同样的事情)。有人可以告诉我如何选择一个列表中不存在于另一个列表中的所有项目吗?

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? If I were using TSQL, I would do SELECT * NOT IN (), but I don't think LINQ allows that.

基本上,我有一个通过在其他两个列表之间匹配项目而形成的列表。我需要找到第一个列表中没有找到匹配项的所有项目。有人可以在下面的第二个 LINQ 查询中用可以实现此目标的查询填充星星吗?如果我使用 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.***

采纳答案by Dimitri

Try using .Exceptextension method (docs):

尝试使用.Except扩展方法(文档)

var result = list1.Except(list2);

will give you all items in list1that are not in list2.

会给你所有list1不在list2.

回答by JaredPar

The easiest way is to use the Exceptmethod.

最简单的方法是使用Except方法。

var deletedItems = list1.Except(joinItems);

This will return the set of items in list1that's not contained in joinItems

这将返回list1未包含在的项目集joinItems

回答by Nalan Madheswaran

Try this:

尝试这个:

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