如何扁平化与LINQ EX pression嵌套对象 [英] How to flatten nested objects with linq expression
本文介绍了如何扁平化与LINQ EX pression嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图拉平这样的嵌套对象:
公共类图书
{
公共字符串名称{;组; }
公众的IList<第二章>章{获得;组; }
}
公共类章
{
公共字符串名称{;组; }
公众的IList<第>页面{获得;组; }
}
公共类页
{
公共字符串名称{;组; }
}
让我做出了榜样。这是我拥有的数据
图书:临LINQ的
{
第1章:你好的LINQ
{
第1页,
页2,
第3页
},
第2章:C#语言增强功能
{
第4页
},
}
我要寻找的结果是以下单位名单:
临LINQ的,你好LINQ的,1
临LINQ的,你好LINQ的,第2页
临LINQ的,你好LINQ的,第3页
临LINQ的,C#语言的增强,第4页
我怎么能做到这一点?我可以做一个的选择新的的,但我已经告诉一个的SelectMany就足够了。
解决方案
myBooks.SelectMany(B => b.Chapters
.SelectMany(C => c.Pages
。选择(p值=> b.Name +,+ c.Name +,+ p.Name)));
I am trying to flatten nested objects like this:
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; }
}
Let me make an example. This is the data I have
Book: Pro Linq
{
Chapter 1: Hello Linq
{
Page 1,
Page 2,
Page 3
},
Chapter 2: C# Language enhancements
{
Page 4
},
}
The result I am looking for is the following flat list:
"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"
How could I accomplish this? I could do it with a select new but I've been told that a SelectMany would be enough.
解决方案
myBooks.SelectMany(b => b.Chapters
.SelectMany(c => c.Pages
.Select(p => b.Name + ", " + c.Name + ", " + p.Name)));
这篇关于如何扁平化与LINQ EX pression嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文