views:

123

answers:

1

Is there an easy way to get the relative complement of two sets? Perhaps using LINQ?

I have to find the relative compliment of a set A relative to B. Both A and B are of type HashSet<T> but I think the algorithm could be made more general (IEnumerable<T> or even ISet<T>)?

I could use a solution in either VB.NET or C#.

+10  A: 

Have you tried Enumerable.Except?

setB.Except(setA)

Example:

HashSet<int> setB = new HashSet<int> { 1, 2, 3, 4, 5 };
HashSet<int> setA = new HashSet<int> { 1, 3, 5, 7 };
HashSet<int> result = new HashSet<int>(setB.Except(setA));

foreach (int x in result)
    Console.WriteLine(x);

Result:

2
4
Mark Byers
thanks so much!!!
SFun28