LINQ Except, Intersect and Union Method/ Operator in C#

Introduction

This article shows how to use expect, intersect and union of LINQ methods in C# and their differences. These are very effective functions of LINQ that confuse me every time. Here I will explain how to use these methods or functions when working with LINQ. These can decrease your development time when working with lists, arrays and collections.

For example, suppose you have two lists and you are told to determine the common elements from the two lists. How will you do it without LINQ? You will use a loop to find the common elements of both lists. But you can do this task in a single line of code using of LINQ functions.

Getting Started

LINQ provides a convenient syntax and many useful methods for operating with collections of objects. All these methods are in the System.Linq namespace. The following explains the details of these functions with code examples.

Except

This is the LINQ extension method that subtracts elements from a collection. For example this will remove elements of the first entities that are elements in the second entities and that will be returned as a third entity.

Code Example

  1. int[] ints1 = { 5, 3, 9, 7, 5, 9, 3, 7 };  
  2. int[] ints2 = { 8, 3, 6, 4, 4, 9, 1, 0 };  
    Console.WriteLine("Elements of FirstArray(ints1):{ 5, 3, 9, 7, 5, 9, 3, 7 }");  
  3. Console.WriteLine("Elements of SecondArray(ints2):{ 8, 3, 6, 4, 4, 9, 1, 0 }");  
  4. int[] Except = ints1.Except(ints2).ToArray();  
  5. Console.WriteLine("Except Result");  
  6. foreach (int num in Except)  
  7. {  
  8.    Console.WriteLine("{0} ", num);  
  9. }  

Result

  1. 5  
  2. 7  
Summary

The Except extension method provides a fast way to use set logic. It removes all the elements from one array found in another array. This reduces the need for complex foreach loops.

Intersect

Intersect returns the common elements of both entities and returns the result as a new entity. For example, there are two lists, the first list contains 1, 2 and 3 the and second list contains 3, 5 and 6. Then the intersect operator will return 3 as the result because 3 exists in both lists.

Code Example

  1. int[] FirstArray = { 1, 2, 3, 8, 9, 10 };  
  2. int[] SecondArray = { 2, 3, 4, 5, 6, 7 };  
    Console.WriteLine("Elements of FirstArray:{ 1, 2, 3,8,9,10 }");  
  3. Console.WriteLine("Elements of SecondArray:{ 2, 3, 4,5,6,7 }");  
  4. Console.WriteLine("Intersect Result");  
  5. int[] Results = FirstArray.Intersect(SecondArray).ToArray();  
  6. foreach (int Result in Results)  
  7. {  
  8.   Console.WriteLine("{0} ", Result);  
  9. }  

Result

  1. 2  
  2. 3  
Summary

We computed the intersection of two integer arrays using a declarative syntax, rather than an imperative loop construct.

Union

The Union operator will combine elements of both entities and return the result as a third entity. The following code example shows how to use Union to obtain the union of two sequences of integers.

Code Example
  1. string[] a = new string[] { "a""b""c""d" };  
  2. string[] b = new string[] { "d""e""f""g" };  
  3. Console.WriteLine("Elements of First array(a):{ a,b,c,d}");  
  4. Console.WriteLine("Elements of Second array(b):{ d,e,f,g}");  
  5. string[] UnResult = a.Union(b).ToArray();  
  6. Console.WriteLine("Union Result");  
  7. foreach (string s in UnResult)  
  8.  {  
  9.     Console.WriteLine(s);  
  10.  }  
Result
  1. a  
  2. b  
  3. c  
  4. d  
  5. e  
  6. f  
  7. g  
Summary
With Union, we combine collections. An imperative approach would involve a hash table or Dictionary. But the Union method can resolve duplicates automatically. This leads to higher levels of code simplicity.
 
FullCode
  1. class Program  
  2.  {  
  3.      static void Main(string[] args)  
  4.      {  
  5.          //Calling expect method  
  6.          ExpectMethod();  
  7.   
  8.          //Calling IntersectMethod  
  9.          IntersectMethod();  
  10.          //Calling Union Method  
  11.          UnionMethod();  
  12.          Console.ReadLine();  
  13.      }  
  14.      private static void ExpectMethod()  
  15.      {  
  16.          int[] ints1 = { 5, 3, 9, 7, 5, 9, 3, 7 };  
  17.          int[] ints2 = { 8, 3, 6, 4, 4, 9, 1, 0 };  
  18.   
  19.          Console.WriteLine("Elements of FirstArray(ints1):{ 5, 3, 9, 7, 5, 9, 3, 7 }");  
  20.          Console.WriteLine("Elements of SecondArray(ints2):{ 8, 3, 6, 4, 4, 9, 1, 0 }");  
  21.   
  22.          int[] Except = ints1.Except(ints2).ToArray();  
  23.          Console.WriteLine("Expect Result");  
  24.          foreach (int num in Except)  
  25.          {  
  26.              Console.WriteLine("{0} ", num);  
  27.          }  
  28.   
  29.      }  
  30.      private static void IntersectMethod()  
  31.      {  
  32.          int[] FirstArray = { 1, 2, 3, 8, 9, 10 };  
  33.          int[] SecondArray = { 2, 3, 4, 5, 6, 7 };  
  34.          Console.WriteLine("Elements of FirstArray:{ 1, 2, 3,8,9,10 }");  
  35.          Console.WriteLine("Elements of SecondArray:{ 2, 3, 4,5,6,7 }");  
  36.          Console.WriteLine("Intersect Result");  
  37.          int[] Results = FirstArray.Intersect(SecondArray).ToArray();  
  38.   
  39.          foreach (int Result in Results)  
  40.          {  
  41.              Console.WriteLine("{0} ", Result);  
  42.          }  
  43.      }  
  44.       
  45.      private static void UnionMethod()  
  46.      {  
  47.          string[] a = new string[] { "a""b""c""d" };  
  48.          string[] b = new string[] { "d""e""f""g" };  
  49.   
  50.   
  51.          Console.WriteLine("Elements of First array(a):{ a,b,c,d}");  
  52.          Console.WriteLine("Elements of Second array(b):{ d,e,f,g}");  
  53.          string[] UnResult = a.Union(b).ToArray();  
  54.          Console.WriteLine("Union Result");  
  55.          foreach (string s in UnResult)  
  56.          {  
  57.              Console.WriteLine(s);  
  58.          }  
  59.      }  
  60.  }   
 Result

 
Conclusion

I hope you will have learned the use of the extension functions of LINQ explained hrere and their differences. 


Similar Articles