Ram*_*eef 12 c# linq-to-objects list hierarchical-data
MyClass包括ID ParentID与List<MyClass>作为Children
我的名单MyClass像这样
ID ParentID
1 0
2 7
3 1
4 5
5 1
6 2
7 1
8 6
9 0
10 9
Run Code Online (Sandbox Code Playgroud)
输出(分层列表)为 List<MyClass>
1 __ 3
|__ 5__ 4
|__ 7__ 2__ 6__ 8
|__ 11
9 __10
Run Code Online (Sandbox Code Playgroud)
在linq中实现这一目标的最简单方法是什么?
PS:ParentID没有排序
编辑:
我的尝试:
class MyClass
{
public int ID;
public int ParentID;
public List<MyClass> Children = new List<MyClass>();
public MyClass(int id, int parent_id)
{
ID = id;
ParentID = parent_id;
}
}
Run Code Online (Sandbox Code Playgroud)
初始化样本数据并尝试访问分层数据
List<MyClass> items = new List<MyClass>()
{
new MyClass(1, 0),
new MyClass(2, 7),
new MyClass(3, 1),
new MyClass(4, 5),
new MyClass(5, 1),
new MyClass(6, 2),
new MyClass(7,1),
new MyClass(8, 6),
new MyClass(9, 0),
new MyClass(10, 9),
new MyClass(11, 7),
};
Dictionary<int, MyClass> dic = items.ToDictionary(ee => ee.ID);
foreach (var c in items)
if (dic.ContainsKey(c.ParentID))
dic[c.ParentID].Children.Add(c);
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,很多我不想要的东西仍然在字典中
JLR*_*she 40
如果在过滤之前构建父子关系,则此处不需要递归.由于列表的成员保持相同的对象,只要您将列表的每个成员与其直接子项相关联,就会构建所有必需的关系.
这可以分为两行:
items.ForEach(item => item.Children = items.Where(child => child.ParentID == item.ID)
.ToList());
List<MyClass> topItems = items.Where(item => item.ParentID == 0).ToList();
Run Code Online (Sandbox Code Playgroud)
Sar*_*rin 16
对于分层数据,您需要递归 - foreach循环是不够的.
Action<MyClass> SetChildren = null;
SetChildren = parent =>
{
parent.Children = items
.Where(childItem => childItem.ParentID == parent.ID)
.ToList();
//Recursively call the SetChildren method for each child.
parent.Children
.ForEach(SetChildren);
};
//Initialize the hierarchical list to root level items
List<MyClass> hierarchicalItems = items
.Where(rootItem => rootItem.ParentID == 0)
.ToList();
//Call the SetChildren method to set the children on each root level item.
hierarchicalItems.ForEach(SetChildren);
Run Code Online (Sandbox Code Playgroud)
items是您使用的相同列表.注意如何SetChildren在自身内调用该方法.这就构成了层次结构.