176-linq-set-operators-union-intersection-except-in-c

If we want to use LINQ Set Operators in C#, then set operations such as union, intersection and except are really one line of code. Take a look at following examples.
Intersection:

int[] set1 = { 1, 2, 3, 5 };
int[] set2 = { 2, 3, 4, 0 };
var intersect = set1.Intersect(set2);
string str_write;
str_write = “Intersection is:” + System.Environment.NewLine;

foreach (int n in intersect)

{

str_write += n.ToString() + ” “;

}

Union:

int[] set1 = { 1, 2, 3, 5 };
int[] set2 = { 2, 3, 4, 0 };
var union = set1.Union(set2);

Except:

int[] set1 = { 1, 2, 3, 5 };
int[] set2 = { 2, 3, 4, 0 };
var except = set1.Except(set2);

int[] transformed = except.ToArray();
string display = String.Join(“,”,transformed);
MessageBox.Show(display);

Concat:

var concat = set1.Concat(set2);

So, LINQ has very rich library of set methods for easy implementation on set operations.

External links:

LINQ Set Operators in C# on Microsoft
LINQ Set Operators in C# on geekswithblogs

Posted in c-sharp-code-examples

Leave a Reply

Your email address will not be published. Required fields are marked *

*