Determine the relative complement of two IEnumerable<T> sets in .NET
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&开发者_开发技巧gt;
)?
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
精彩评论