So I understand how to remove duplicates in a list when it comes to strings and int, etc by using Distinct() from Linq. But how do you remove duplicates based on a specific attribute of an object?
For example, I have a TimeMetric class. This TimeMetric class has two attributes: MetricText and MetricTime. I have a list of TimeMetrics called MetricList. I want to remove any duplicates TimeMetric with the same MetricText attribute. The TimeMetric value can be the same but if any TimeMetric has the same MetricText, it must be unduplicated.
You need to use the second overload of
Distinctthat takes anIEqualityComparer<TimeMetric>instance as a second parameter. Define a comparer like this:Important note: The above code does not check for the case where the
MetricTextproperty isnull(and it sounds like it could be, since it’s most probably astring). You should do that and return0fromGetHashCodeifMetricTextisnull. On the other hand, if the type ofMetricTextis a value type, you don’t need to perform any modification.And then: