I am following a previous post on stackoverflow about removing duplicates from a List in C#.
If
is some user defined type like:
For this task I don't necessarily thinks implementing IComparable is the obvious solution. You might want to sort and test for uniqueness in many different ways.
I would favor implementing a IEqualityComparer
:
sealed class ContactFirstNameLastNameComparer : IEqualityComparer
{
public bool Equals (Contact x, Contact y)
{
return x.firstname == y.firstname && x.lastname == y.lastname;
}
public int GetHashCode (Contact obj)
{
return obj.firstname.GetHashCode () ^ obj.lastname.GetHashCode ();
}
}
And then use System.Linq.Enumerable.Distinct
(assuming you are using at least .NET 3.5)
var unique = contacts.Distinct (new ContactFirstNameLastNameComparer ()).ToArray ();
PS. Speaking of HashSet<>
Note that HashSet<>
takes an IEqualityComparer<>
as a constructor parameter.