在C#中从平面列表创建嵌套列表 [英] Creating a Nested List from a Flat List in C#

查看:45
本文介绍了在C#中从平面列表创建嵌套列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有以下课程:

public class NavigationItem
{
    public int ID { get; set; }
    public string Title { get; set; }
    public int ParentID { get; set; }
    public List<NavigationItem> Children { get; set; }
}

public class FlatItem
{
    public int ID { get; set; }
    public string Title { get; set; }
    public int ParentID { get; set; }
}

我有一个示例数据,如下:

I have a sample data as follows:

+====+============+==========+
| ID |   Title    | ParentID |
+====+============+==========+
|  1 | Google     |          |
+----+------------+----------+
|  2 | Microsoft  |          |
+----+------------+----------+
|  3 | Oracle     |          |
+----+------------+----------+
|  4 | Gmail      |        1 |
+----+------------+----------+
|  5 | Sheets     |        1 |
+----+------------+----------+
|  6 | Adsense    |        1 |
+----+------------+----------+
|  7 | Azure      |        2 |
+----+------------+----------+
|  8 | SharePoint |        2 |
+----+------------+----------+
|  9 | Office     |        2 |
+----+------------+----------+
| 10 | Java       |        3 |
+----+------------+----------+
| 11 | Word       |        9 |
+----+------------+----------+
| 12 | Excel      |        9 |
+----+------------+----------+
| 13 | PowerPoint |        9 |
+----+------------+----------+

我已经有代码从上面的示例数据中提取所有信息,并将其转换为 List< FlatItem> 对象.

I already have the code to pull all the information from the sample data above and turn it into a List<FlatItem> object.

什么是最好的方法,以便我可以拥有一个 List< NavigationItem> 对象,该对象看起来像下面的东西:

What's the best approach so that I can have a List<NavigationItem> object which will look like something below:

  • Google
    • Gmail
    • 片材
    • AdSense
    • 天蓝色
    • SharePoint
    • 办公室
      • 单词
      • Excel
      • PowerPoint
      • Java

      我正在考虑创建一种递归方法,以遍历我的 List< FlatItem> ,然后以某种方式将其结构化为NavigationItem的嵌套列表.

      I'm thinking of creating a recursive method to loop through my List<FlatItem> then structure it in a way to be a nested list of NavigationItem.

      推荐答案

      无需递归.您可以使用LINQ轻松构建结构:

      No need for recursion. You could use LINQ to build the structure easily:

      List<FlatItem> flatItems = ...;
      
      var navigationItems = flatItems.Select(
          i => new NavigationItem { ID = i.ID, Title = i.Title, ParentID = i.ParentID }
      ).ToList();
      
      foreach (var i in navigationItems)
          i.Children = navigationItems.Where(n => n.ParentID == i.ID).ToList();
      
      // get Google, Microsoft, Oracle items
      var rootNavigationItems = navigationItems.Where(n => n.ParentID == 0);
      

      这篇关于在C#中从平面列表创建嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆