Hugo Hilário
Hugo Hilário

Reputation: 2908

LINQ - Getting all child records from all parents

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

Upvotes: 4

Views: 3771

Answers (3)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26635

I suggest you to change List<Bar> property name to Bars.

And firstly use SelectMany(). It projects each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence. And then use Select() to project each element of a new sequence as you wish.

var result = myList.SelectMany(x => x.Bars).Select(x => x.Value).ToList();

Upvotes: 7

marcinn
marcinn

Reputation: 1786

Use SelectMany instead of Select

var result = LIST1.SelectMany(x => x.LIST2.Select(y => y.Value)).Tolist();

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499770

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;

Upvotes: 12

Related Questions