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.

Phil H
  • 19,928
  • 7
  • 68
  • 105

1 Answers1

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);    
}
Ani
  • 111,048
  • 26
  • 262
  • 307