Published on

SymmetricExceptWith using LINQ

image
Authors
  • avatar
    Name
    David Jimenez
    Twitter

The class Hashset<T> provides the method SymmetricExceptWith. Assume that A = { 1, 2, 3 } and B = { 3, 4, 5 }. Calling A.SymmetricExceptWith(B) modifies A to contain only the elements that were in A or in B, but not both. So, A would become { 1, 2, 4, 5 }.

We could derive this method using the available operations in LINQ. First we can calculate the union: A.Union(B) = { 1, 2, 3, 4, 5 }. Next, we find the intersect: A.Intersect(B) = { 3 }. Finally, we remove the intersect from the union: union.Except(intersect) = { 1, 2, 4, 5 }. And this is the equivalent to SymmetricExceptWith.

var A = new HashSet<int>(new int[] { 1,2,3 });
var B = new HashSet<int>(new int[] { 3,4,5 });
 
var union = A.Union(B);
var intersect = A.Intersect(B);
var symmetricExcept = union.Except(intersect);

What would happen if right after running the above code, we called A.SymmetricExceptWith(B), and then ran A.SetEquals(symmetricExcept). Would it return true or false?

var A = new HashSet<int>(new int[] { 1,2,3 });
var B = new HashSet<int>(new int[] { 3,4,5 });
 
var union = A.Union(B);
var intersect = A.Intersect(B);
var symmetricExcept = union.Except(intersect);
 
A.SymmetricExceptWith(B);
Console.WriteLine(A.SetEquals(symmetricExcept)) // What does this print?;