[HowTo] Linq Count Granchild items from an object with .SelectMany()

Lets say you have the following structure :
Product
   -> Zone
      -> Category
         -> Item
Meaning a Product has multiple Zones with multiple Categories with multiple Items
Lets say we need to select the count of items for each product in a simple distinct list of product.

Linq query using .SelectMany() :

xyzDataContext dc = new xyzDataContext();
List pl = from p in dc.Products
                   select new { p.name,
                                ItemCount = p.Zones.SelectMany(z => z.Categories).SelectMany(c => c.Items).Count()
                              };
dc.Dispose();

Leave a Reply