I have two collections a and b. I would like to compute the set of items in either a or b, but not in both (a logical exc
Use HashSet directly - it has a SymmetricExceptWith method:
HashSet data = new HashSet(a);
data.SymmetricExceptWith(b);
EDIT: If you want to maintain the order, here's an alternative:
HashSet data = new HashSet(a);
data.IntersectWith(b);
foreach (T t in a.Concat(b))
{
if (!data.Contains(t))
{
yield return t;
}
}
This has the following important differences:
a and b are iterated over twice. In some cases that could be a very bad thing - you could call ToList on each of them to start with to retain a buffer.If there are duplicates in either a or b, they will be yielded multiple times. If you wanted to avoid this you could keep a set of already-yielded values. At this point, it would be equivalent to:
a.Concat(b).Except(a.Intersect(b))
That's still only two set operations instead of the three in your original code though.