C# 查找 listA 是否包含不在 listB 中的任何元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9524681/
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 07:44:15  来源:igfitidea点击:

Find if listA contains any elements not in listB

c#linq

提问by Tony

I have two lists:

我有两个清单:

List<int> listA     
List<int> listB

How to check using LINQ if in the listAexists an element wchich deosn't exists in the listB? I can use the foreachloop but I'm wondering if I can do this using LINQ

如何使用 LINQ 检查是否listA存在一个不存在的元素listB?我可以使用foreach循环,但我想知道是否可以使用 LINQ

采纳答案by cadrell0

listA.Except(listB)will give you all of the items in listA that are not in listB

listA.Except(listB)将为您提供 listA 中不在 listB 中的所有项目

回答by SLaks

if (listA.Except(listB).Any())

回答by dasblinkenlight

You can do it in a single line

您可以在一行中完成

var res = listA.Where(n => !listB.Contains(n));

This is not the fastest way to do it: in case listBis relatively long, this should be faster:

这不是最快的方法:如果listB比较长,这应该更快:

var setB = new HashSet(listB);
var res = listA.Where(n => !setB.Contains(n));

回答by the_joric

listA.Any(_ => listB.Contains(_))

:)

:)

回答by Onur

List has Contains method that return bool. We can use that method in query.

列表具有返回布尔值的包含方法。我们可以在查询中使用该方法。

List<int> listA = new List<int>();
List<int> listB = new List<int>();
listA.AddRange(new int[] { 1,2,3,4,5 });
listB.AddRange(new int[] { 3,5,6,7,8 });

var v = from x in listA
        where !listB.Contains(x)
        select x;

foreach (int i in v)
    Console.WriteLine(i);

回答by Joost00719

This piece of code compares two lists both containing a field for a CultureCode like 'en-GB'. This will leave non existing translations in the list. (we needed a dropdown list for not-translated languages for articles)

这段代码比较了两个列表,这两个列表都包含一个像“en-GB”这样的 CultureCode 字段。这将在列表中留下不存在的翻译。(我们需要一个用于文章未翻译语言的下拉列表)

var compared = supportedLanguages.Where(sl => !existingTranslations.Any(fmt => fmt.CultureCode == sl.Culture)).ToList();

var compared = supportedLanguages.Where(sl => !existingTranslations.Any(fmt => fmt.CultureCode == sl.Culture)).ToList();

回答by Jnr

Get the difference of two lists using Any(). The Linq Any()function returns a boolean if a condition is met but you can use it to return the difference of two lists:

使用Any()获取两个列表的差异。Any()如果满足条件,Linq函数将返回一个布尔值,但您可以使用它来返回两个列表的差值:

var difference = ListA.Where(a => !ListB.Any(b => b.ListItem == a.ListItem)).ToList();