Why C# LINQ Distinct(f=>f.propertyname) doesn’t work?
Why C# LINQ Distinct() doesn’t work?
2231
17-Aug-2023
Updated on 18-Aug-2023
Aryan Kumar
18-Aug-2023The
Distinct()method in LINQ is used to remove duplicates from a sequence. TheDistinct()method takes an optional parameter that specifies the comparer to use when comparing elements. If the parameter is 0, the default comparer is used. The default comparer compares elements by their GetHashCode() method.The GetHashCode() method returns a hash code for an object. The hash code is used to quickly compare elements in a hash table. However, the GetHashCode() method does not guarantee that two objects with different values will have different hash codes. This is why the
Distinct()method with a parameter of 0 does not work.To use the
Distinct()method to remove duplicates, you need to specify a comparer that guarantees that two objects with different values will have different hash codes. You can use theIEqualityComparerinterface to create a custom comparer.The following code is an example of how to use the
Distinct()method with a custom comparer:C#
In this code, the
PersonComparerclass implements theIEqualityComparerinterface and provides a custom comparer for thePersonclass. TheEquals()method compares the names of twoPersonobjects and returns a value indicating whether the two objects are equal. TheGetHashCode()method returns a hash code for aPersonobject.The
distinctPeoplevariable is a list that contains only the distinctPersonobjects from thepeoplelist.