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 :
The Distinct clause removes duplicate values from a collection. The Distinct clause returned the unique elements from the input sequence.
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…
The Union clause returns the union of two sets. The result set contains unique elements that are common in two sets.
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…
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.
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…
The Except clause returned the element from the first input sequence that are not in the second input sequence.
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…