I have a couple of tables where there are one to many relationships. Let's say I have a Country table, a State table with a FK to Country, and a City table with a FK to State.
I'd like to be able to create a count of all Cities for a given country, and also a count of cities based on a filter - something like:
foreach( var country in Model.Country ) {
total = country.State.All().City.All().Count() ;
filtered = country.State.All().City.Any(c=>c.field == value).Count();
}
Obviously, this doesn't work - is there any way to do this?
Update:
I can iterate thru the objects:
foreach (var item in Model ) {
... other stuff in here ...
int tot = 0;
int filtered = 0;
foreach (var state in item.State)
{
foreach (var city in state.City)
{
tot++;
if (city.Field == somevalue)
filtered ++;
}
}
... other stuff in here ...
}
but that doesn't seem very elegant.
Update: @AD has a couple of suggestions, but what worked to solve the problem was:
int tot = item.States.Sum(s=>s.City.Count);
int filtered = item.States.Sum(s=>s.City.Where(c=>c.Field == somevalue).Count());