构建使用对象列表的树 [英] Building a tree using a list of objects

查看:82
本文介绍了构建使用对象列表的树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有物业编号和PARENT_ID对象的列表。
我想建立一个树的孩子和家长联系起来。
1父母可能有几个孩子,有一个对象,这将是所有对象的祖先。

I have a list of objects with property id and parent_id.
I want to build a tree to link up those children and parents.
1 parent may have several children and there is an object which will be the ancestor of all objects.

什么是最快的算法来实现呢?
我使用C#作为编程语言,但其他语言也没关系。

What's the fastest algorithm to implement that?
I use C# as programming language, but other languages are also okay.

推荐答案

这样的东西应该做的伎俩:

Something like that should do the trick :

public List<Node> MakeTreeFromFlatList(IEnumerable<Node> flatList)
{
    var dic = flatList.ToDictionary(n => n.Id, n => n);
    var rootNodes = new List<Node>();
    foreach(var node in flatList)
    {
        if (node.ParentId.HasValue)
        {
            Node parent = dic[node.ParentId.Value];
            node.Parent = parent;
            parent.Children.Add(node);
        }
        else
        {
            rootNodes.Add(node);
        }
    }
    return rootNodes;
}

(假设的ParentId是可空&LT; INT&GT; ,并且是空的根节点)

(assuming that ParentId is a Nullable<int>, and is null for root nodes)

这篇关于构建使用对象列表的树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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