Set Operators (LINQ)
Posted by Rajinder
Last Updated: July 22, 2012
  1485

Set operations in LINQ refer to query operations that produce a result set that is based on the presence or absence of equivalent elements within the same or separate collections (or sets).

Distinct

This sample uses Distinct to remove duplicate elements in a sequence of factors of 300.

public void Linq() 
{ 
    int[] factorsOf300 = { 22355 }; 
  
    var uniqueFactors = factorsOf300.Distinct(); 
  
    Console.WriteLine("Prime factors of 300:"); 
    foreach (var f in uniqueFactors) 
    { 
        Console.WriteLine(f); 
    } 
}

Union

public void Linq() 
{ 
    int[] numbersA = { 0245689 }; 
    int[] numbersB = { 13578 }; 
  
    var uniqueNumbers = numbersA.Union(numbersB); 
  
    Console.WriteLine("Unique numbers from both arrays:"); 
    foreach (var n in uniqueNumbers) 
    { 
        Console.WriteLine(n); 
    } 
}

Intersect

This sample uses Intersect to create one sequence that contains the common values shared by both arrays.

public void Linq() 
{ 
    int[] numbersA = { 0245689 }; 
    int[] numbersB = { 13578 }; 
  
    var commonNumbers = numbersA.Intersect(numbersB); 
  
    Console.WriteLine("Common numbers shared by both arrays:"); 
    foreach (var n in commonNumbers) 
    { 
        Console.WriteLine(n); 
    } 
}

Except

This sample uses Except to create a sequence that contains the values from numbersAthat are not also in numbersB.

public void Linq() 
{ 
    int[] numbersA = { 0245689 }; 
    int[] numbersB = { 13578 }; 
  
    IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB); 
  
    Console.WriteLine("Numbers in first array but not second array:"); 
    foreach (var n in aOnlyNumbers) 
    { 
        Console.WriteLine(n); 
    } 
}