I have two models:
class Foo
{
public List<Bar> Bars { get; set; }
}
class Bar
{
public int Value { get; set; }
}
Having an instance of List<Foo>
, how can I get all Value
using a LINQ query?
Thank you all
SelectMany
is normally the way to flatten hierarchies, so:
var values = myList.SelectMany(foo => foo.Bar)
.Select(bar => bar.Value);
The SelectMany
will give you an IEnumerable<Bar>
, and then the Select
projects that sequence of Bar
objects to the Value
property of each, returning an IEnumerable<int>
.
As a query expression, this would be:
var values = from foo in myList
from bar in foo.Bar
select bar.Value;
See more on this question at Stackoverflow