How do I use a custom comparer with the Linq Distinct method?

前端 未结 1 436
余生分开走
余生分开走 2020-12-20 13:37

I was reading a book about Linq, and saw that the Distinct method has an overload that takes a comparer. This would be a good solution to a problem I have where I want to ge

1条回答
  •  一整个雨季
    2020-12-20 14:28

    You're implementing your comparer as an IComparer, the LINQ method overload requires an implementation of IEqualityComparer:

    private class GribulatorComparer : IEqualityComparer {
      public bool Equals(Gribulator g1, Gribulator g2) {
        return g1.ID == g2.ID;
      }
    }
    

    edit:

    For clarification, the IComparer interface can be used for sorting, as that's basically what the Compare() method does.

    Like this:

    items.OrderBy(x => new ItemComparer());
    
    private class ItemComparer : IComparer
    {
        public int Compare(Item x, Item y)
        {
            return x.Id.CompareTo(y.Id)
        }
    }
    

    Which will sort your collection using that comparer, however LINQ provides a way to do that for simple fields (like an int Id).

    items.OrderBy(x => x.Id);
    

    0 讨论(0)
提交回复
热议问题