你能帮忙复制下面出现在linq表达式中的“for”语句吗?
List<RawData> rawList = [{ "address":"adr1","id":[11,12,13],"city":"NYC"},{"address":"adr2","id":[22,23],"city":"Boston"}, {"address":"adr3","id":[77],"city":"Chicago"}];
List<Data> list = new List<Data>();
foreach (var item in rawList)
{
foreach (var id in item.idList)
{
Data d = new Data
{
id = id,
address = item.address,
city = item.city
};
list.Add(d);
}
}
答案 0 :(得分:5)
使用SelectMany
方法在LINQ中展平:
var res = rawList
.SelectMany(item => item.idList
.Select(id => new Data {
id = id,
address = item.address,
city = item.city
})
).ToList();
一旦你理解了它的作用,其余部分就是不言自明的。