How to make categories, subcategories, subsubcategories with mvc?
I have three classes
public class CountryListViewModel { public IEnumerable<CountryViewModel> Countries { get; set; } } public class CountryViewModel { public string CountryName { get; set; } public string State { get; set; } public IEnumerable<CityViewModel> Cities { get; set; } } public class CityViewModel { public string CityName { get; set; } public string CityLink { get; set; } }
Using linq to entity grouping by country and it works as designed. but I also have to group by state. Could you please help me to change my query to group first by country and than by state?
var query = from c in _db.MyTable
where c.IsActive && c.Country == country
group c by c.Country
into loc
开发者_运维知识库 select new CountryViewModel()
{
CountryName = loc.Key,
Cities = loc.Select(s => new CityViewModel() { CityName = s.City, CityLink = s.City }).Distinct()
};
I found solution by myself
var query = from c in _db.MyTable
where c.IsActive && c.Country == country
group c by new{ c.Country, c.State}
into loc
select new CountryViewModel()
{
CountryName = loc.Key.Country,
State = loc.Key.State,
Cities = loc.Select(s => new CityViewModel() { CityName = s.City, CityLink = s.City }).Distinct()
};
var q = from i in query
group i by i.state into st
select new with { .State = st.Key,
.Countries = (from c in st group c by c.Country into ctr
select new with {.Country = ctr.Key,
.Cities = ctr})
No Idea if this works, just typed it in here without testing or looking at your datamodel.
精彩评论