我试图使用lambda从表/结果集中获取数据,并生成包含其他对象列表的对象,我有一个元素列表,例如:
continent | country | state
europe | france | paris
europe | france | rouen
europe | spain | madrid
europe | italy | milan
america | usa | ohio
america | usa | kansas
america | usa | texas
america | usa | iowa
america | mexico | colima
america | mexico | tabasco
africa | niger | maradi
africa | niger | tahoua
africa | niger | niamey 我需要把它按大陆和国家分组,以便生成一个有对象列表的对象列表.类似于:
- spain
- madrid
- italy
- milan
- mexico
- colima
- tabasco
我所拥有的是:
DataTable.GroupBy(g => new
{
g.continent,
g.country
})
.Select(s => s.First()).ToList().ForEach(n =>
{
_continentals.Add(new Continent
{
name = n.continent,
countries = new List<Country>
{
new Country
{
name = n.country,
states = new List<State>
{
new State
{
name = n.state
}
}
}
}
}
}但是它不起作用,我也不知道如何修复它(它没有按照正确的顺序生成/分组元素)。
发布于 2014-01-20 16:50:07
您需要按大陆分组,然后将其中的每一组按国家分组,而不是根据对大陆/国家进行一次分组:
var query = DataTable.GroupBy(item => item.continent,
(key, group) => new
{
Continent = key,
Countries = group.GroupBy(item => item.country)
});https://stackoverflow.com/questions/21239603
复制相似问题