Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ - Getting all child records from all parents

Tags:

c#

linq

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

like image 557
Hugo Hilário Avatar asked Dec 01 '22 00:12

Hugo Hilário


1 Answers

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;
like image 105
Jon Skeet Avatar answered Dec 17 '22 11:12

Jon Skeet