Edited: I didn't follow the link in the solution posted by Zoltán Zörgő before my posting. It is essentially the same as what I posted here. I have upvoted his solution.
Distinct()
has an overload that takes an
IEqualityComparer<TSource>
parameter. So you could implement that interface and then use the
Distinct()
pattern you already know.
Like this:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var metrics = new List<TimeMetric>();
Random r = new Random();
for (int i = 0; i < 10; i++)
{
var item = new TimeMetric();
item.MetricText = (i | 1).ToString();
item.MetricTime = TimeSpan.FromTicks(r.Next());
metrics.Add(item);
Console.WriteLine("metric[{0}]: MetricText = \"{1}\", MetricTime = {2}",
i, item.MetricText, item.MetricTime);
}
var NoDuplicates = metrics.Distinct(new TimeMetricTextComparer());
int ix = 0;
foreach (var item in NoDuplicates)
{
Console.WriteLine("NoDuplicates[{0}]: MetricText = \"{1}\", MetricTime = {2}",
ix++, item.MetricText, item.MetricTime);
}
}
}
class TimeMetric
{
public string MetricText { get; set; }
public TimeSpan MetricTime { get; set; }
}
class TimeMetricTextComparer : IEqualityComparer<TimeMetric>
{
#region IEqualityComparer<TimeMetric> Members
public bool Equals(TimeMetric x, TimeMetric y)
{
return string.Equals(x.MetricText, y.MetricText);
}
public int GetHashCode(TimeMetric obj)
{
return obj.MetricText.GetHashCode();
}
#endregion
}
}
In the comparer class, Equals and GetHashCode
must be consistent. If
Equals
is
true
for two
TimeMetric
instances, then
GetHashCode
must return the
same value for both.