4

I am diffing two dictionaries, and I want the set of all keys in or or other dictionary but not both (I don't care about order). Since this only involves the keys, we can do this with the IEnumerables of the keys of the dictionaries.

The easy way, involving 2 passes:

return first.Keys.Except(second.Keys).Concat(second.Keys.Except(first.Keys));

We can concat because the Excepts guarantee the lists will be entirely different.

But I sense there is a better, linqy way to do it.

3
  • 2
    possible duplicate of LINQ and set difference Feb 5, 2013 at 13:15
  • So you want the Distinct list of values without duplicates?
    – Bob.
    Feb 5, 2013 at 13:15
  • I do, and yes this is therefore a dupe. Did not see that previously. Voted to close.
    – Phil H
    Feb 5, 2013 at 13:20

1 Answer 1

3

I prefer a non-LINQy way:

var set = new HashSet<KeyType>(first.Keys);
set.SymmetricExceptWith(second.Keys);

Here's an alternative (but not better) LINQy way to yours:

var result = first.Keys.Union(second.Keys)
                       .Except(first.Keys.Intersect(second.Keys));

If you're looking for something (possibly) more performant:

var result = new HashSet<KeyType>();

foreach(var firstKey in first.Keys)
{
    if(!second.ContainsKey(firstKey))
        result.Add(firstKey);    
}

foreach(var secondKey in second.Keys)
{
    if(!first.ContainsKey(secondKey))
        result.Add(secondKey);    
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.