How to flatten nested objects with linq expression

abx78 picture abx78 · Jun 21, 2011 · Viewed 65.5k times · Source

I am trying to flatten nested objects like this:

public class Book
{
    public string Name { get; set; }
    public IList<Chapter> Chapters { get; set; }
}

public class Chapter
{
    public string Name { get; set; }
    public IList<Page> Pages { get; set; }
}


public class Page
{
    public string Name { get; set; }
}

Let me make an example. This is the data I have

Book: Pro Linq 
{ 
   Chapter 1: Hello Linq 
   {
      Page 1, 
      Page 2, 
      Page 3
   },
   Chapter 2: C# Language enhancements
   {
      Page 4
   },
}

The result I am looking for is the following flat list:

"Pro Linq", "Hello Linq", "Page 1"
"Pro Linq", "Hello Linq", "Page 2"
"Pro Linq", "Hello Linq", "Page 3"
"Pro Linq", "C# Language enhancements", "Page 4"

How could I accomplish this? I could do it with a select new but I've been told that a SelectMany would be enough.

Answer

Yuriy Faktorovich picture Yuriy Faktorovich · Jun 21, 2011
myBooks.SelectMany(b => b.Chapters
    .SelectMany(c => c.Pages
        .Select(p => b.Name + ", " + c.Name + ", " + p.Name)));