【问题标题】:In C#, how can i determine if a list has any item from another list?在 C# 中,我如何确定一个列表是否包含另一个列表中的任何项目?
【发布时间】:2013-11-08 00:52:21
【问题描述】:

我有一个清单:

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# linq collections


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-25
        • 2023-03-18
        • 1970-01-01
        • 1970-01-01
        • 2021-04-25
        相关资源
        最近更新 更多