Search code examples
c#algorithmlinqset-difference

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


I used except to find the modified objects, but except takes a comparator and only returns the difference.

What is the best algorithm to return such result?

Thanks.


Solution

  • As I understand, you have two KeyValuePair like that:

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

    What you want is a simply joining two sequence based on matching keys. For this you can use Enumerable.Join. Then, you just need to filter the result with Where() method:

    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();
    

    Or, as a second option you can just iterate over the second list and get matching elements in the first list:

    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();
    

    But, I prefer Join().