我想基于单个列表创建新的列表列表。 我有一个像
这样的清单public class OfficeLocator
{
public String id{ get; set; }
public string Geography{ get; set; }
public string Country{ get; set; }
public string State{ get; set; }
public string OfficeName{ get; set; }
}
我正在尝试准备树状结构列表
GeographyName="Asia",
{
Country = "China",
{
State = "Hunan",
{
{
OfficeId = "1",
OfficeName = "Office 1"
},
{
OfficeId = "2",
OfficeName = "Office 2"
}
},
State = "Hubei"
{
{
OfficeId = "3",
OfficeName = "Office 3"
}
}
},
Country = "India",
{
State = "Maharashtra",
{
{
OfficeId = "4",
OfficeName = "Office 4"
},
{
OfficeId = "5",
OfficeName = "Office 5"
}
},
State = "Punjab"
{
{
OfficeId = "6",
OfficeName = "Office 6"
}
}
},
},
GeographyName="Europe",
{
Country = "UK",
{
State = "York",
{
{
OfficeId = "7",
OfficeName = "Office 7"
},
{
OfficeId = "8",
OfficeName = "Office 8"
}
}
}
}
我尝试在地理和国家/地区使用一些小组。 但我没有得到所需的输出 我可以使用循环逻辑来获得结果,但我想避免它并尝试使用linq。
答案 0 :(得分:4)
这样的东西?
var allRegionGroups = allOfficeLocators
.GroupBy(ol => ol.Geography)
.Select(gGroup => new
{
GeographyName = gGroup.Key,
Countries = gGroup
.GroupBy(ol => ol.Country)
.Select(cGroup => new
{
Country = cGroup.Key,
States = cGroup
.GroupBy(ol => ol.State)
.Select(sGroup => new
{
State = sGroup.Key,
OfficeList = sGroup
.Select(ol => new { OfficeId = ol.id, ol.OfficeName })
.ToList()
})
.ToList()
})
.ToList()
})
.ToList();
如何访问匿名类型的所有属性:
foreach (var region in allRegionGroups)
{
string geographyName = region.GeographyName;
var allCountries = region.Countries;
foreach (var c in allCountries)
{
string country = c.Country;
var allStates = c.States;
// and so on...
}
}
答案 1 :(得分:0)
GroupBy,在这种情况下有一些方便的重载:
var query = locations.GroupBy(
x => x.Geography,
(a, aGroup) => new
{
A = a,
Items = aGroup.GroupBy(
x => x.Country,
(b, bGroup) => new
{
B = b,
Items = bGroup.GroupBy(
x => x.State,
(c, cGroup) => new
{
B = c,
Items = cGroup.Select(i => new {i.Id, i.OfficeName})
})
})
});
读写起来更清楚一点 如果需要,Anonimised对象可以由您自己的类替换。
答案 2 :(得分:0)
你可以达到和提到的相同的结果 但不是使用方法语法, 依赖查询语法来争论更好的可读性
var projection = from location in locations
group location by location.Geography into geographies
select new
{
Geography = geographies.Key,
Countries = from geography in geographies
group geography by geography.Country into countries
select new
{
Country = countries.Key,
States = from country in countries
group country by country.State into states
select new
{
State = states.Key,
Offices = from state in states
select new
{
Id = state.Id,
Office = state.Office,
}
}
}
};
,最终结果如下所示