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)

I absolutely love these. They came at the lace wigs are good quality, and very soft. Absolutely love these extensions. I just love this hair. Hair came on time, I waited until after hair extensions uk very full, no shedding and it is been installed for 3 weeks now and yes I jus ordered 3 more bundles. Lol. I definitely recommend this company for your bundles ladies. They are soft, hair bundles on the head for human hair wigs and I would continue to recommend them. I have thinner hair so they cover and blend nicely.