How to flatten nested objects with linq expression
我正在尝试展开这样的嵌套对象:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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; } } |
让我举个例子。这是我的数据
1 2 3 4 5 6 7 8 9 10 11 12 13 | Book: Pro Linq { Chapter 1: Hello Linq { Page 1, Page 2, Page 3 }, Chapter 2: C# Language enhancements { Page 4 }, } |
我要查找的结果是以下简单列表:
1 2 3 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" |
我怎么能做到?我可以选择一个新的,但我已经被告知选择多就足够了。
1 2 3 | myBooks.SelectMany(b => b.Chapters .SelectMany(c => c.Pages .Select(p => b.Name +"," + c.Name +"," + p.Name))); |
一assuming
1 2 3 4 | 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}; |
1 2 3 4 5 6 7 8 | myBooks.SelectMany(b => b.Chapters .SelectMany(c => c.Pages .Select(p => new { BookName = b.Name , ChapterName = c.Name , PageName = p.Name }); |
我想这是好的,与从尤利的评论和linqpad梅辛与我有这个。
请注意,我有一个网页,书籍,章节,我一人,companyperson(丛书)(部分)和公司(页)
1 2 3 4 5 6 7 8 | 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 }; |
或
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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博客斯科特档案/2008/03/25/inner-outer-lets-all-join-together-with-linq.aspx