Linq Distinct!


I have a List of books- each book has a category – i want to find out all the unique categories involved, given a list of books- i knew i could do this with linq, but not quite sure how!

It turned out to be easy..

List<Category> categories = _books.Select(i => i.Category).Distinct();

There was a minor complication however- Distinct obviously needs to be able to compare different instances of Category- you can supply a delegate to a custom EquityComparer class- otherwise it will simply check if this is the same instance of the object, which will (probably) always come back false rendering your distinct useless. So i created this;

    public class CategoryComparer : IEqualityComparer<Category>
    {
        public bool Equals(Category x, Category y)
        {
            return x.Id == y.Id;
        }

        public int GetHashCode(Category obj)
        {
            return obj.Id.GetHashCode();
        }
    }

then updated my linq to use it..

List<Category> categories = _books.Select(i => i.Category).Distinct(new CategoryComparer());
  1. No comments yet.
(will not be published)