我正在尝试扁平化嵌套对象,如下所示:
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"
我怎么才能做到这一点呢?我可以用精选的new来实现,但有人告诉我SelectMany就足够了。
发布于 2011-06-22 00:49:16
myBooks.SelectMany(b => b.Chapters
.SelectMany(c => c.Pages
.Select(p => b.Name + ", " + c.Name + ", " + p.Name)));
发布于 2011-06-22 00:58:32
假设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};
发布于 2015-02-02 17:41:09
myBooks.SelectMany(b => b.Chapters
.SelectMany(c => c.Pages
.Select(p => new
{
BookName = b.Name ,
ChapterName = c.Name ,
PageName = p.Name
});
https://stackoverflow.com/questions/6428940
复制相似问题