在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);