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

前端 未结 1 435
余生分开走
余生分开走 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<T>, the LINQ method overload requires an implementation of IEqualityComparer:

    private class GribulatorComparer : IEqualityComparer<Gribulator> {
      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<Item>
    {
        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)
提交回复
热议问题