C# LINQ Set Operators

Updated on     Kisan Patel

The LINQ Set operators are used to perform the mathematical set-type operations on the sequences.

The four different types of Set operators in LINQ :

  1. Distinct
  2. Union
  3. Intersect
  4. Except

The Distinct clause

The Distinct clause removes duplicate values from a collection. The Distinct clause returned the unique elements from the input sequence.

linq-distinct-operator

For Example, the following query returned distinct country from Customers table.

NorthwindEntities _db = new NorthwindEntities();
var customers = _db.Customers.Select(x => new { x.Country}).Distinct();
foreach (var customer in customers)
{
      Console.WriteLine(customer.Country);
}

the above code will produce below output…

linq-distinct-operator1

The Union clause

The Union clause returns the union of two sets. The result set contains unique elements that are common in two sets.

linq-union-operator

For Example,

NorthwindEntities _db = new NorthwindEntities();
var CityCount = _db.Customers.Select(x => new { x.City })
                                      .Union(_db.Employees.Select(x => new { x.City }))
                                      .Count();
Console.WriteLine("The number of cities in Northwind : " + CityCount);

the above code will produce below output…

linq-union-opearator-eample

The Intersect clause

The Intersect clause returns the set intersection and the element appear in each of the two collections. So The The Intersect clause returned the element that are common to both of the input sequences.

linq-intersect-operator

For Example,

NorthwindEntities _db = new NorthwindEntities();
var CityCount = _db.Customers.Select(x => new { x.City })
                                      .Intersect(_db.Employees.Select(x => new { x.City }))
                                      .Count();
Console.WriteLine("The number of cities in Northwind : " + CityCount);

the above code will produce below output…

linq-intersect-operator-example

The Except clause

The Except clause returned the element from the first input sequence that are not in the second input sequence.

linq-except-operator

For Example,

NorthwindEntities _db = new NorthwindEntities();
var CityCount = _db.Customers.Select(x => new { x.City })
                                      .Except(_db.Employees.Select(x => new { x.City }))
                                      .Count();
Console.WriteLine("The number of cities in Northwind : " + CityCount);

the above C# code will produce below output…

linq-except-operator-example


C# LINQ

Leave a Reply