What are union, intersect and except operators in Linq C#?


Union

Union combines multiple collections into a single collection and returns a resultant collection with unique elements

Intersect

Intersect returns sequence elements which are common in both the input sequences

Except

Except returns sequence elements from the first input sequence that are not present in the second input sequence

Example

class Program{
   static void Main(){
      int[] count1 = { 1, 2, 3, 4 };
      int[] count2 = { 2, 4, 7 };
      var resultUnion = count1.Union(count2);
      var resultIntersect = count1.Intersect(count2);
      var resultExcept = count1.Except(count2);
      System.Console.WriteLine("Union");
      foreach (var item in resultUnion){
         Console.WriteLine(item);
      }
      System.Console.WriteLine("Intersect");
      foreach (var item in resultIntersect){
         Console.WriteLine(item);
      }
      System.Console.WriteLine("Except");
      foreach (var item in resultExcept){
         Console.WriteLine(item);
      }
      Console.ReadKey();
   }
}

Output

Union
1
2
3
4
7
Intersect
2
4
Except
1
3

Updated on: 04-Aug-2020

383 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements