Home > Back-end >  .NET replacing values where keys match
.NET replacing values where keys match

Time:11-16

This is a simple question. I have two lists ListA and ListB they are both full of the same type of objects with keys, but everything else (besides key) can be different, the size the values etc..... I want to replace the values in ListA with values from ListB where they match (without O(mn), since I could do it easily with loop inside loop) and the values that do exist in ListB but don't exist in ListA should be added to ListA, this can be two operations I don't mind but I want to keep the difficulty below O(n^2) or O(mn)

I tried using intersect but I am not sure how to move on from there I can get rows that match, but how to replace add them... Is beyond me.

CodePudding user response:

If your class overrides Equals and GetHashCode(to compare the Key) or/and implements IEqualityComparer<YourClass>, you can use Intersect and Except. However, in this case you should use a (left-outer-)Join which is also a set based approach:

var query =
    from b in listB
    join a  in listA on b.Key equals a.Key into ba
    from a_join in ba.DefaultIfEmpty()
    select (OnlyInB: a_join == null, A: a_join, B: b);
    

foreach(var x in query)
{
    if(x.OnlyInB)
    {
        listA.Add(x.B);
    }
    else
    {
        CompareAndTransferProperties(x.A, x.B);
    }
}

and a method CompareAndTransferProperties which does what it name suggests:

private static void CompareAndTransferProperties(MyClass a, MyClass b)
{
    // your task ...
}
  • Related