How Except Method work in LINQ

Introduction

The Except method is a LINQ extension method which  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.

Example

will remove elements of the first list that are elements in the second list and that will be returned as a third list.  See the code below which explains the work of Except.

Code Example
  1. int[] list1 = { 5, 3, 9, 7, 5, 9, 3, 7 };        
  2. int[] list2 = { 8, 3, 6, 4, 4, 9, 1, 0 };        
  3. Console.WriteLine("Elements of FirstArray(list1 ):{ 5, 3, 9, 7, 5, 9, 3, 7 }");        
  4. Console.WriteLine("Elements of SecondArray(list2 ):{ 8, 3, 6, 4, 4, 9, 1, 0 }");        
  5. int[] Except = list1 .Except(list2 ).ToArray();        
  6. Console.WriteLine("Except Result");        
  7. foreach (int num in Except)        
  8. {        
  9.    Console.WriteLine("{0} ", num);        
  10. }    
Result
  1. 5  
  2. 7  
In the above code, list2 array contains all the similar element of array list1 except the 5 and 7. Hence the Except function returned a new array with element 5 and 7.

Summary

With this demonstrator, i hope you must get ideas how the Except function is working.