‘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.
We will have another class which populates and returns list of Employees,
Now creating an instance of DistinctDemo and applying ‘Distinct’ to get distinct values,
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.
Distinct can be applied by passing ‘EmployeeComparer’ object.
var empList = distintDemo.EmployeeList.Distinct(new EmployeeComparer());