在C#中,如何确定列表是否包含其他列表中的任何项目?

leo*_*ora 6 c# linq collections

我有一个清单:

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)"
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*rvy 19

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

if(list.Intersect(list2).Any())
    DoStuff();
Run Code Online (Sandbox Code Playgroud)