本文介绍了如何使用 linq 表达式展平嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试像这样展平嵌套对象:

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"

我怎么能做到这一点?我可以用 select new 来实现,但有人告诉我 SelectMany 就足够了.

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 表达式展平嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-15 08:09