我有两个型号:
class Foo
{
public List<Bar> Bars { get; set; }
}
class Bar
{
public int Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
有一个实例List<Foo>,我怎样才能Value使用LINQ查询?
谢谢你们
Jon*_*eet 12
SelectMany 通常是扁平化层次结构的方式,因此:
var values = myList.SelectMany(foo => foo.Bar)
.Select(bar => bar.Value);
Run Code Online (Sandbox Code Playgroud)
该SelectMany会给你一个IEnumerable<Bar>,然后将Select项目是序列Bar对象的Value每个属性,并返回IEnumerable<int>.
作为查询表达式,这将是:
var values = from foo in myList
from bar in foo.Bar
select bar.Value;
Run Code Online (Sandbox Code Playgroud)
我建议你把List<Bar>属性名改为Bars.
并首先使用SelectMany().它将序列的每个元素IEnumerable<T>投影到a 并将生成的序列展平为一个序列.然后根据需要Select()用于投影新序列的每个元素.
var result = myList.SelectMany(x => x.Bars).Select(x => x.Value).ToList();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2337 次 |
| 最近记录: |