Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>)?

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

like image 733
SFun28 Avatar asked Jun 02 '10 18:06

SFun28


1 Answers

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
like image 133
Mark Byers Avatar answered Sep 21 '22 13:09

Mark Byers