LINQ Statement that parses multiple collection and gets a single List

I would like to know if there is a better/faster way to write the following LINQ Statement.

First let me show you my class definition:

public class FooA
{
    public List<FooB> ListFooB { get; set; }
}

public class FooB
{
    public List<FooC> ListFooC { get; set; }
}

public class FooC
{
    public List<FooD> ListFooD { get; set; }
}

Now I have a class that stores a list of FooA, and I need to work with the FooDs inside the FooC definition, so my LINQ looks like the following:

public class MagicFoo
{
    public List<FooA> ListFooA { get; set; }

    public void DoSomeMagicWithFooD()
    {
        var fooDs = from a in ListFooA
                    from b in a.ListFooB
                    from c in b.ListFooC
                    from d in c.ListFooD
                    select d;

        foreach (var fooD in fooDs)
        {
            //Do your magic with fooD...
        }
    }
}

Is there a better/faster way to write the LINQ?

Jon Skeet
people
quotationmark

Well, in terms of efficiency that's creating a lot of extra objects for the sake of transparent identifiers in the translation from query expressions to SelectMany calls. You could convert it to:

var fooDs = ListFooA.SelectMany(a => a.ListFooB
                        .SelectMany(b => b.ListFooC
                           .SelectMany(c =>  c.ListFooD)));

That's more efficient, but less readable.

people

See more on this question at Stackoverflow