问题
How to group SubGroup to create list of Continents where each Continent has it own counties and each country has its own cities like this table
Here is the t-sql:
select Continent.ContinentName, Country.CountryName, City.CityName
from Continent
left join Country
on Continent.ContinentId = Country.ContinentId
left join City
on Country.CountryId = City.CountryId
and the result of t-sql:
I tried this but it groups the data in wrong way i need to group exactly like the above table
var Result = MyRepository.GetList<GetAllCountriesAndCities>("EXEC sp_GetAllCountriesAndCities");
List<Continent> List = new List<Continent>();
var GroupedCountries = (from con in Result
group new
{
con.CityName,
}
by new
{
con.ContinentName,
con.CountryName
}
).ToList();
List<Continent> List = GroupedCountries.Select(c => new Continent()
{
ContinentName = c.Key.ContinentName,
Countries = c.Select(w => new Country()
{
CountryName = c.Key.CountryName,
Cities = c.Select(ww => new City()
{
CityName = ww.CityName
}
).ToList()
}).ToList()
}).ToList();
回答1:
You need to group everything by continent, these by country and the countries by city:
List<Continent> List = MyRepository.GetList<GetAllCountriesAndCities>("EXEC sp_GetAllCountriesAndCities")
.GroupBy(x => x.ContinentName)
.Select(g => new Continent
{
ContinentName = g.Key,
Countries = g.GroupBy(x => x.CountryName)
.Select(cg => new Country
{
CountryName = cg.Key,
Cities = cg.GroupBy(x => x.CityName)
.Select(cityG => new City { CityName = cityG.Key })
.ToList()
})
.ToList()
})
.ToList();
回答2:
You should apply grouping twice
var grouped = Result
.GroupBy(x => x.CountryName)
.GroupBy(x => x.First().ContinentName);
var final = grouped.Select(g1 => new Continent
{
ContinentName = g1.Key,
Countries = g1.Select(g2 => new Country
{
CountryName = g2.Key,
Cities = g2.Select(x => new City { CityName = x.CityName }).ToList()
}).ToList()
});
回答3:
I know this is old, but I wanted to mention a much easier way per microsoft that is a bit more readable. This is an example with only 2 levels though but it will most likely work for others who reach this page (like me)
var queryNestedGroups =
from con in continents
group con by con.ContinentName into newGroup1
from newGroup2 in
(from con in newGroup1
group con by con.CountryName)
group newGroup2 by newGroup1.Key;
The documentation for that is at https://docs.microsoft.com/en-us/dotnet/csharp/linq/create-a-nested-group and is using a Student object as an example
I do want to mention that the method they use for printing is harder than just creating a quick print function on your continent object
来源:https://stackoverflow.com/questions/39081806/linq-grouping-subgroup