In LINQ, set operators are used to perform operations that involve comparing and combining sequences of data. They are useful for tasks like finding unique elements, checking for overlaps, or combining results from multiple sequences. There are following Set operators.
The Distinct operator is used to remove duplicate elements from a sequence.
List<int> numbers = new List<int> { 1, 2, 2, 3, 4, 4, 5 };
var distinctNumbers = numbers.Distinct();
foreach (var number in distinctNumbers)
{
Console.WriteLine(number); // Output: 1, 2, 3, 4, 5
}
The Union operator combines two sequences and returns a sequence of unique elements that appear in either of the sequences.
Example
List<int> numbers1 = new List<int> { 1, 2, 3, 4 };
List<int> numbers2 = new List<int> { 3, 4, 5, 6 };
var unionNumbers = numbers1.Union(numbers2);
foreach (var number in unionNumbers)
{
Console.WriteLine(number); // Output: 1, 2, 3, 4, 5, 6
}
The Intersect operator returns a sequence of elements that are present in both sequences.
Example
List<int> numbers1 = new List<int> { 1, 2, 3, 4 };
List<int> numbers2 = new List<int> { 3, 4, 5, 6 };
var intersectNumbers = numbers1.Intersect(numbers2);
foreach (var number in intersectNumbers)
{
Console.WriteLine(number); // Output: 3, 4
}
The Except operator returns a sequence of elements that are in the first sequence but not in the second sequence.
Example
List<int> numbers1 = new List<int> { 1, 2, 3, 4 };
List<int> numbers2 = new List<int> { 3, 4, 5, 6 };
var exceptNumbers = numbers1.Except(numbers2);
foreach (var number in exceptNumbers)
{
Console.WriteLine(number); // Output: 1, 2
}
The Concat operator combines two sequences into a single sequence. Note that Concat does not remove duplicates; it simply appends one sequence to another.
Example
List<int> numbers1 = new List<int> { 1, 2, 3 };
List<int> numbers2 = new List<int> { 4, 5, 6 };
var concatenatedNumbers = numbers1.Concat(numbers2);
foreach (var number in concatenatedNumbers)
{
Console.WriteLine(number); // Output: 1, 2, 3, 4, 5, 6
}
The Zip operator combines two sequences into a single sequence of pairs, using a specified function to combine corresponding elements.
Example
List<string> names = new List<string> { "Rohatash", "Mohit", "Saurav" };
List<int> ages = new List<int> { 30, 25, 40 };
var zipped = names.Zip(ages, (name, age) => new { Name = name, Age = age });
foreach (var item in zipped)
{
Console.WriteLine($"{item.Name} is {item.Age} years old");
}
// Output:
// Rohatash is 30 years old
// Mohit is 25 years old
// Saurav is 40 years old