如何使用 linq 表达式压平嵌套对象

我正在尝试压平这样的嵌套对象:

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; }
}

让我举个例子,这是我所掌握的数据

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

我要寻找的结果是以下的单位清单:

"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"

我怎么能做到呢?我可以用 选择新的做到这一点,但是我被告知一个 SelectMany 就足够了。

82392 次浏览
myBooks.SelectMany(b => b.Chapters
.SelectMany(c => c.Pages
.Select(p => b.Name + ", " + c.Name + ", " + p.Name)));

假设 books是一个图书目录:

var r = from b in books
from c in b.Chapters
from p in c.Pages
select new {BookName = b.Name, ChapterName = c.Name, PageName = p.Name};

我也在尝试这样做,从 Yuriy 的评论和 linqPad 的混乱,我有这个. 。

注意,我没有书、章节、页面,我有人(书)、公司人(章节)和公司(页面)

from person in Person
join companyPerson in CompanyPerson on person.Id equals companyPerson.PersonId into companyPersonGroups
from companyPerson in companyPersonGroups.DefaultIfEmpty()
select new
{
ContactPerson = person,
ContactCompany = companyPerson.Company
};

或者

Person
.GroupJoin (
CompanyPerson,
person => person.Id,
companyPerson => companyPerson.PersonId,
(person, companyPersonGroups) =>
new
{
person = person,
companyPersonGroups = companyPersonGroups
}
)
.SelectMany (
temp0 => temp0.companyPersonGroups.DefaultIfEmpty (),
(temp0, companyPerson) =>
new
{
ContactPerson = temp0.person,
ContactCompany = companyPerson.Company
}
)

我使用的参考站点: http://odetocode.com/blogs/scott/archive/2008/03/25/inner-outer-lets-all-join-together-with-linq.aspx

myBooks.SelectMany(b => b.Chapters
.SelectMany(c => c.Pages
.Select(p => new
{
BookName = b.Name ,
ChapterName = c.Name ,
PageName = p.Name
});