Assume I have a class called MyClass that has two properties (int Id and a string Name). I want to populate a List of these MyClass objects from another collection but I want only the unique ones. This other collection is a 3rd party object that has a property named ‘Properties’ that is just an array of values, the first two of which correspond to the Id and Name values I care about. There can be duplicates in this collection so I want only the unique ones.
It seems like this should do the trick but it does not, it returns all the items regardless of dupes. What am I doing wrong here?
List<MyClass> items = (from MyClass mc in collectionOfProps
select new MyClass() {
Id = collectionOfProps.Properties[0],
Name = collectionOfProps.Properties[1] }).Distinct().ToList();
The problem is likely that
MyClassdoes not implementIEquatable<MyClass>as well as overrideEqualsandGetHashCode.In order to make
Distinct()work the way you want, you have to implementIEquatable<T>. Otherwise, it uses the default (reference equality) for checking, which means it would only determine the elements were not distinct if they were the same exact instance.