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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With