removing duplicates from a list C#

后端 未结 3 1264
予麋鹿
予麋鹿 2020-12-15 13:09

I am following a previous post on stackoverflow about removing duplicates from a List in C#.

If is some user defined type like:



        
3条回答
  •  粉色の甜心
    2020-12-15 13:20

    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.

提交回复
热议问题