Using set operation in LINQ

There are many set operation that are required to be performed while working with any kind of data. This can be done very easily with the help of LINQ methods available for this functionality. Below are some of the examples of the set operation with LINQ.

Finding distinct values in the set of data.

We can use the distinct method to find out distinct values in a given list.

    int[] factorsOf300 = { 2, 2, 3, 5, 5 };

    var uniqueFactors = factorsOf300.Distinct();

We can also use the set operation of UNION with the help of UNION method in the LINQ. The Union method takes another collection as a parameter and returns the distinct union values in  both the list. Below is an example.

    int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
    int[] numbersB = { 1, 3, 5, 7, 8 };
    var uniqueNumbers = numbersA.Union(numbersB);

We can also get the set operation of INTERSECT with the help of the INTERSECT method. Below is an example.

    int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };

    int[] numbersB = { 1, 3, 5, 7, 8 };

   

    var commonNumbers = numbersA.Intersect(numbersB);

 

We can also find the difference between the 2 sets of data with the help of except method.

 

    int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };

    int[] numbersB = { 1, 3, 5, 7, 8 };

   

    IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB);

 

Vikram

1 Comment

Comments have been disabled for this content.