LINQ - 从所有 parents 中获取所有 child 记录
LINQ - Getting all child records from all parents
我有两个模型:
class Foo
{
public List<Bar> Bars { get; set; }
}
class Bar
{
public int Value { get; set; }
}
拥有 List<Foo>
的实例,如何使用 LINQ 查询获取所有 Value
?
谢谢大家
我建议您将 List<Bar>
属性 名称更改为 Bars
。
然后首先使用SelectMany()
. It projects each element of a sequence to an IEnumerable<T>
and flattens the resulting sequences into one sequence. And then use Select()
根据需要投影新序列的每个元素。
var result = myList.SelectMany(x => x.Bars).Select(x => x.Value).ToList();
SelectMany
通常是扁平化层次结构的方式,因此:
var values = myList.SelectMany(foo => foo.Bar)
.Select(bar => bar.Value);
SelectMany
会给你一个 IEnumerable<Bar>
,然后 Select
将 Bar
对象序列投射到 Value
属性,返回一个 IEnumerable<int>
.
作为查询表达式,这将是:
var values = from foo in myList
from bar in foo.Bar
select bar.Value;
使用SelectMany
代替Select
var result = LIST1.SelectMany(x => x.LIST2.Select(y => y.Value)).Tolist();
我有两个模型:
class Foo
{
public List<Bar> Bars { get; set; }
}
class Bar
{
public int Value { get; set; }
}
拥有 List<Foo>
的实例,如何使用 LINQ 查询获取所有 Value
?
谢谢大家
我建议您将 List<Bar>
属性 名称更改为 Bars
。
然后首先使用SelectMany()
. It projects each element of a sequence to an IEnumerable<T>
and flattens the resulting sequences into one sequence. And then use Select()
根据需要投影新序列的每个元素。
var result = myList.SelectMany(x => x.Bars).Select(x => x.Value).ToList();
SelectMany
通常是扁平化层次结构的方式,因此:
var values = myList.SelectMany(foo => foo.Bar)
.Select(bar => bar.Value);
SelectMany
会给你一个 IEnumerable<Bar>
,然后 Select
将 Bar
对象序列投射到 Value
属性,返回一个 IEnumerable<int>
.
作为查询表达式,这将是:
var values = from foo in myList
from bar in foo.Bar
select bar.Value;
使用SelectMany
代替Select
var result = LIST1.SelectMany(x => x.LIST2.Select(y => y.Value)).Tolist();