给定两个对象列表,如何在 C# 中比较新的 KV?

Given two lists of objects, how do I compare into new KV in C#?

我使用 except 来查找修改后的对象,但是 except 需要一个比较器并且只有 return 的区别。

return 这样的结果的最佳算法是什么?

谢谢。

据我了解,您有两个 KeyValuePair 这样的:

List<KeyValuePair<string, string>> list1 = new List<KeyValuePair<string, string>>();
List<KeyValuePair<string, string>> list2 = new List<KeyValuePair<string, string>>();

您想要的是基于匹配键简单地连接两个序列。为此,您可以使用 Enumerable.Join。然后,您只需要使用 Where() 方法过滤结果:

var result = list2.Join(list1, x => x.Key, y => y.Key, (x, y) => new { x, y })
                  .Where(l => l.x.Value != l.y.Value)
                  .ToList();

或者,作为第二个选项,您可以迭代第二个列表并在第一个列表中获取匹配的元素:

var result = list2.Where(x => list1.Any(y => y.Key == x.Key && y.Value != x.Value))
     .Select(x => new
     {
         NewKVP = new KeyValuePair<string, string>(x.Key, x.Value),
         OldKVP = new KeyValuePair<string, string>(x.Key, list1.Single(z => z.Key == x.Key).Value)
     })
    .ToList();

但是,我更喜欢Join()