LINQ Except Operator

LINQ Except operator comes under Set operators category in LINQ. LINQ Set operators is used for compare two sequences (collections) and find common, missing and unique elements. You can find entire list of set operators here.

Except operator compares two sequences (collections) classes and find those elements which are not present in second sequence. For example. suppose we have a collection A = { 1, 2, 3 } and B = { 1, 3 }. R = A EXCEPT B = { 2 }. 2 element is only available in first collection A and not available in second collection B.

Except operator is an extension method which takes a single parameter of second sequence. Below is the syntax:

By default, exception operator does not work with Custom Types. It compares objects basis on string return by ToString() method. To compare custom types we need to use second overload method of Except method which takes an IEqualityComparer interface as parameter.

IEqualityComparer has two methods Equals and GetHasCode. We need to create a new class which implement this IEqualityComparer interface. Below is the example.

We have created a new class ResidentNameCompare which implement the IEqualityComparer interface. We implement both methods Equals and GetHashCode. We need to implement both methods both are required to compare. In the Equals method implementation, we compare Name property of two Residents objects using string.equals methods and in GetHashCode we return hash code of Name property of Resident object.