【问题标题】:See items that match in two list查看两个列表中匹配的项目
【发布时间】:2011-05-27 01:52:26
【问题描述】:

免得说我有两个列表

列表1:

“汤姆”, “坦率”, “莱西”

列表2:

“弗兰克”, “汤姆”

显示 Tom 和 Fran 被重复需要的查询是什么?

我要比较的列表非常大,如果我执行以下操作:

 var q = from a in List1
         from b in List2
         where a.Name == b.Name
         select a;

这需要很长时间。

【问题讨论】:

    标签: c# linq iequalitycomparer


    【解决方案1】:

    要查看哪些值在列表中重复,您可以使用

    var results = list1.Intersect(list2);
    

    如果您有兴趣匹配项目并为每个项目做点什么,您可以使用Join

    var results = from item1 in list1 
                  join item2 in list2 
                  on item1 equals item2 
                  select new 
                  {
                      // include what you want here
                  };
    

    在您的情况下,由于您正在处理字符串列表,Intersect 似乎是适当的行动方案。如果您要处理公共键上的对象匹配列表,您可能会选择加入列表并投影结果。

    【讨论】:

      【解决方案2】:

      你应该使用Intersect:

      var items = List1.Intersect(List2); // Tom, Frank
      

      【讨论】:

        【解决方案3】:

        你可以使用intersect:

        List<string> list3 = list1.Intersect(list2).ToList();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-26
          • 2012-12-30
          • 2013-08-12
          • 2012-07-21
          相关资源
          最近更新 更多