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#.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With