Joining parent and child collection in LINQ for a single merged output

Indeed .SelectMany(...) is the answer. Another usage is:

var data = dogs
    .SelectMany(d => d.DogFriends.Select(df => new { d, df })
    .Select(x =>
        // Now you can use both d and df
        new NewObject {
            fieldOne = x.d.propertyOne,
            fieldTwo = x.d.propertyTwo
            fieldThree = x.df.propertyOne
        }
    )
    .ToArray();

Even simpler is to use the query LINQ notation. This basically translates to the above at compile time.

var data = from d in dogs
           from df in d.DogFriends
           select new NewObject {
               fieldOne = d.propertyOne,
               fieldTwo = d.propertyTwo
               fieldThree = df.propertyOne
           }

Tags:

C#

Linq