嵌套为 LINQ 与链接链接列表
本文关键字:链接 列表 LINQ 嵌套 | 更新日期: 2023-09-27 18:37:13
我有一个列表中的列表。我只需要列表中的一个值,并且可以使用嵌套的foreach获取我的结果,但我想使用某种类型的LINQ查询。
我的代码:
var myCity = from c in CountryLists
select (from city in c.stateList
where city.name == passedInValue
select city.name).FirstorDefault();
这会将 myCity 作为某种类型的列表返回,所有值均为 null,除非找到匹配项的位置。
我不想为了找到名字而浏览城市列表。我怎么在 myCity 中只有一个值;空或所需的名称?
首先,使用 SelectMany
展平列表,然后FirstOrDefault
过滤:
CountryList.SelectMany(c => c.stateList).FirstOrDefault(d => d.Name == passedInValue);
请注意,由于FirstOrDefault
可以采用谓词,因此实际上并不需要Where
子句。
如何使用 SelectMany:
var city = CountryLists
.SelectMany(x => x.stateList)
.FirstOrDefault(x => x.name == passedInValue);
您可以像其他人指出的那样使用SelectMany
(我自己更喜欢该解决方案),但是,如果您想要查询语法,则可以使用多个from
子句(有关更多示例,请查看 MSDN 文档):
var city = (from c in CountryLists
from city in c.stateList
where city.name == passedInValue
select city.name).FirstOrDefault();
它相当于SelectMany
方法解决方案,无论如何它都在幕后使用它。