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());
Related posts:
- Entity Framework 4.1 Code First (With One to Many relationship) Code Example
- Syndicating to RSS using the built in .net SyndicationFeed classes
- Reading & Writing XML Files with LINQ
- Creating a re-usable shopping basket with Generics in C#
- Creating an Order/ Order Details style view using ASP.net MVC2 & Entity Framework 4










