LINQ Get Count of 2nd level detail table
I'm trying to get the count of records from a detail table, and it's detail table in LINQ and I'm hitting a road block.
Lets say I have 3 tables in this structure:
Header
Detail
Items
I would like to see all Header items with the count of Detail and the count of it's Ite开发者_JAVA技巧ms.
from h in Header select new {
h.Name,
h.IsEnabled,
DetailCount = h.Details.Count(),
ItemCount = h.Details.Items.Count() <---- Here's the problem
}
You can use SelectMany
:
from h in Header select new {
h.Name,
h.IsEnabled,
DetailCount = h.Details.Count(),
ItemCount = h.Details.SelectMany(d => d.Items).Count()
}
Or if you prefer you could sum the items count of each detail:
from h in Header select new {
h.Name,
h.IsEnabled,
DetailCount = h.Details.Count(),
ItemCount = h.Details.Sum(d => d.Items.Count())
}
精彩评论