(ID / PARENTID)名单分级列表 [英] (ID/ParentID) list to Hierarchical list

查看:305
本文介绍了(ID / PARENTID)名单分级列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MyClass的 ID PARENTID 列表与LT; MyClass的> 孩子

我有这样的 MyClass的列表

ID  ParentID
1   0
2   7
3   1
4   5
5   1
6   2
7   1
8   6
9   0
10  9

输出(分级列表)为列表< MyClass的>

1 __ 3
 |__ 5__ 4
 |__ 7__ 2__ 6__ 8
     |__ 11

9 __10

什么是LINQ实现这一目标的最简单的方法?结果
P.S: 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;
    }
}

初​​始化样本数据,以期达到分层数据

initialize sample data and try to reach hierarchical data

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

你可以看到,很多项目我不想仍然在字典中

as you can see, lots of items I don't want still in the dictionary

推荐答案

有关分层数据,你需要递归 - foreach循环是不够的。

For hierarchical data, you need recursion - a foreach loop won't suffice.

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

项目是您使用相同的列表。注意 SetChildren 方法是如何在自身内部调用。这是构建体的层次结构。

items is the same list you use. Notice how the SetChildren method is called within itself. This is what constructs the hierarchy.

这篇关于(ID / PARENTID)名单分级列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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