在 C# 中,如何确定一个列表是否包含另一个列表中的任何项

本文关键字:列表 是否 一个 包含 另一个 任何项 何确定 | 更新日期: 2023-09-27 18:37:17

>我有一个列表:

var list = new List<string>();
list.Add("Dog");
list.Add("Cat");
list.Add("Bird");
var list2 = new List<string>();
list2.Add("Dog");
list2.Add("Cat"):
if (list.ContainsAny(list2))
{
      Console.Write("At least one of the items in List2 exists in list1)"
}

在 C# 中,如何确定一个列表是否包含另一个列表中的任何项

您正在查看列表的"交集"是否为非空:

if(list.Intersect(list2).Any())
    DoStuff();

你只需要 Enumerable.Intersect,如下所示:

if (list.Intersect(list2).Any())
{
  Console.Write("At least one of the items in List2 exists in list1)"
}

此方法通过使用默认相等比较器来比较值来生成两个序列的集合交集。它返回一个序列,其中包含构成两个序列的集合交集的元素。Enumerable.Any() 方法确定序列是否包含任何元素。