Applying 'Distinct' on Collection of Custom Type

Distinct’ function on the collection of simple types such as List<int>, List<string> etc., works fine. In the case of collection of custom objects such as List<T> where ‘T’ being a type of a class, distinct function may not work.

Let us take an example to illustrate this behavior.

Employees class

We will have another class which populates and returns list of Employees,

class for returns list

Now creating an instance of DistinctDemo and applying ‘Distinct’ to get distinct values,

class

output

As can be seen from the above output , distinct function did not remove duplicate items from the list. To resolve this when applying distinct, a custom comparer object can be passed. Custom Comparer should Implement ‘IEqualityComparer’ interface and provide definition for the comparison.

DistinctDemo

Distinct can be applied by passing ‘EmployeeComparer’ object.

var empList = distintDemo.EmployeeList.Distinct(new EmployeeComparer());

run