如何用LINQexpression式来压缩嵌套的对象
我正在尝试拼合这样的嵌套对象:
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"
我怎么能做到这一点? 我可以用一个select新的,但我已经被告知一个SelectMany就足够了。
myBooks.SelectMany(b => b.Chapters .SelectMany(c => c.Pages .Select(p => b.Name + ", " + c.Name + ", " + p.Name)));
假设books
是一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};
我也试图做到这一点,从尤里的评论和凌乱的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 });
- 在C#中将大文件读入字节数组的最佳方法是什么?
- 在WPF DataGrid中的文本alignment
- 从枚举属性获取枚举
- 等待运营商只能在一个asynchronous方法内使用
- 为什么甚至有可能改变一个私人成员,或在C#中使用reflection运行私有方法?
- 如何以编程方式selectWPF TreeView中的项目?
- 如果我在使用声明结束之前返回,会发生什么情况? 这个configuration会被调用吗?
- 如何在控制台应用程序中添加App.Config文件
- 不能将types'System.Collections.Generic.IEnumerable <AnonymousType#1>'隐式转换为'System.Collections.Generic.List <string>