Part 27 - Union, Intersect and Except operators in LINQ

The following operators belong to Set operators categoryDistinctUnionIntersectExcept

We discussed Distinct operator in Part 26. In this video we will discuss Union, Intersect and Except operators.

Union combines two collections into one collection while removing the duplicate elements.

Example 1: numbers1 and numbers2 collections are combined into a single collection. Notice that, the duplicate elements are removed.

int[] numbers1 = { 1, 2, 3, 4,
5 };

int[] numbers2 = { 1, 3, 6, 7,
8 };

var result = numbers1.Union(numbers2);

foreach (var v in
result)

{

Console.WriteLine(v);

}

Output:

When comparing elements, just like Distinct() method, Union(), Intersect() and Except() methods work in a slightly different manner with complex types like Employee, Customer etc.

Example 2 : Notice that in the output the duplicate employee objects are not removed. This is because, the default comparer is being used which will just check for object references being equal and not the individual property values.

List<Employee> list1 = newList<Employee>()

{

new Employee { ID = 101, Name = "Mike"},

new Employee { ID = 102, Name = "Susy"},

new Employee { ID = 103, Name = "Mary"}

};

List<Employee> list2 = newList<Employee>()

{

new Employee { ID = 101, Name = "Mike"},

new Employee { ID = 104, Name = "John"}

};

var result = list1.Union(list2);

foreach (var v in
result)

{

Console.WriteLine(v.ID
+ "\t" + v.Name);

}

Output :

Example 3 : To solve the problem in Example 2, there are 3 ways1. Use the other overloaded version of Union() method to which we can pass a custom class that implements IEqualityComparer2. Override Equals() and GetHashCode() methods in Employee class3. Project the properties into a new anonymous type, which overrides Equals() and GetHashCode() methods

Project the properties into a new anonymous type, which overrides Equals() and GetHashCode() methods