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 list = new List<TimeMetric> { ... };
var unique = list.Distinct(new MyComparer());
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…