Removing duplicate objects in a list (C#)

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 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());

Need Your Help

generate random 64 bit integer

c++ random 64bit

i need your help and please give me some advice.from programming pearls i have studded that to generate random 30 bit integer we should write like this

Aeroo Report Function not Call

python xml openerp reportlab rml

I'm new in aeroo report, I define function called fill_stars(self, amount): which takes the amount and convert into text format. While i'm going to print report, it gives following error

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.