【问题标题】:Intersect lists on KeyValuePair key?KeyValuePair 键上的相交列表?
【发布时间】:2010-09-13 15:29:43
【问题描述】:

如何根据键插入两个 KeyValuePair 列表?我试过了:

List<KeyValuePair<string, string>> listA = new List<KeyValuePair<string, string>>();
List<KeyValuePair<string, string>> listB = new List<KeyValuePair<string, string>>();
...
var result = listA.Intersect(listB);

这预期不起作用。我是否需要根据密钥编写自己的比较器,或者是否有使用 LINQ/Lambda 的简单方法?

谢谢!

【问题讨论】:

    标签: c# linq list lambda


    【解决方案1】:
    var keysFromB = new HashSet<string>(listB.Select(x => x.Key));
    var result = listA.Where(x => keysFromB.Remove(x.Key));
    

    请注意,此代码通过使用Remove 方法模仿Intersect 的行为。这意味着这两个序列都被视为集合:如果listA 中有多个具有相同键的项,则result 将仅包含其中一项。如果您不希望出现这种行为,请使用 Contains 方法而不是 Remove

    【讨论】:

      【解决方案2】:

      怀疑您确实必须编写自己的比较器 - 至少要使用 Intersect

      您可以使用 MiscUtil 的 ProjectionEqualityComparer 来简化此操作:

      // Ick what a mouthful
      var comparer = ProjectionEqualityComparer<KeyValuePair<string, string>>.Create
             (x => x.Key);
      
      var result = listA.Intersect(listB, comparer);
      

      如果每个列表中的键都是唯一的,则另一个选项是连接:

      var commonPairs = from pairA in listA
                        join pairB in listB on pairA.Key equals pairB.Key
                        select new { pairA, pairB };
      

      【讨论】:

      • 这与我需要的很接近,但我不能确定密钥是否唯一。 (而且我宁愿不引用另一个程序集。)
      • @Alex:链接被短暂破坏了,但我后来修复了它。应该没问题的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-20
      • 2013-04-09
      • 2013-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多