Removing duplicate objects in a list (C#)

You need to use the second overload of Distinct that takes an IEqualityComparer<TimeMetric> instance as a second parameter. Define a comparer like this:

class MyComparer:IEqualityComparer<TimeMetric>
public bool Equals(TimeMetric x,TimeMetric y)
return x.MetricText.Equals(y.MetricText);
public int GetHashCode(TimeMetric obj)
return obj.MetricText.GetHashCode();

Important note: The above code does not check for the case where the MetricText property is null (and it sounds like it could be, since it’s most probably a string). You should do that and return 0 from GetHashCode if MetricText is null. On the other hand, if the type of MetricText is a value type, you don’t need to perform any modification.

And then:

var unique =list.Distinct(newMyComparer());


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s