从对象列表递归地创建对象树结构
本文关键字:创建对象 结构 递归 对象 列表 | 更新日期: 2023-09-27 17:50:28
我在数据库中有如下所示的菜单列表。如何在c#中为下面显示的数据创建一个类似对象树的结构?
Id MenuLabel ParentMenuId
1 Home 0 // Main Menu
2 MyAccounts 0 // Main Menu
3 MyProfile 2 // Sub Menu, parent menu is MyAccounts
4 Trade 0 // Main Menu
5 Stock 4 // Sub Menu, parent menu is Trade
6 Bonds 4 // Sub Menu, parent menu is Trade
理想情况下,我需要c#中的对象结构像这样。是否有可用的最佳实践或模式?Home
MyAccounts
----MyProfile
Trade
----Stock
----Bonds
使用字典。parentDict将创建您正在查找的结构。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("MenuLabel", typeof(string));
dt.Columns.Add("ParentMenuId", typeof(int));
dt.Rows.Add(new object[] {1, "Home",0}); // Main Menu
dt.Rows.Add(new object[] {2, "MyAccounts",0}); // Main Menu
dt.Rows.Add(new object[] {3, "MyProfile",2}); // Sub Menu, parent menu is MyAccounts
dt.Rows.Add(new object[] {4, "Trade", 0}); // Main Menu
dt.Rows.Add(new object[] {5, "Stock", 4}); // Sub Menu, parent menu is Trade
dt.Rows.Add(new object[] {6, "Bonds", 4 }); // Sub Menu, parent menu is Trade
Dictionary<int, List<DataRow>> parentDict = dt.AsEnumerable()
.GroupBy(x => x.Field<int>("ParentMenuId"), y => y)
.ToDictionary(x => x.Key, y => y.ToList());
Dictionary<int, DataRow> dict = dt.AsEnumerable()
.GroupBy(x => x.Field<int>("Id"), y => y)
.ToDictionary(x => x.Key, y => y.FirstOrDefault());
int menu = 3;
List<DataRow> parents = new List<DataRow>();
for (int row = menu; (int)dict[row]["ParentMenuId"] != 0; row = (int)dict[row]["ParentMenuId"])
{
parents.Add(dict[(int)dict[row]["ParentMenuId"]]);
}
}
}
}