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

本文关键字:嵌套 对象 表达式 何使用 linq | 更新日期: 2023-09-27 17:59:58

我正在尝试压平嵌套对象,如下所示:

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就足够了。

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

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};
myBooks.SelectMany(b => b.Chapters
    .SelectMany(c => c.Pages
        .Select(p => 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