将平面集合转换为分层集合的递归方法? [英] Recursive method to convert flat collection to hierarchal collection?

查看:98
本文介绍了将平面集合转换为分层集合的递归方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在这个问题上停留了几天,希望能提出一些想法或对解决这个问题有所帮助. 我有一些物件

I have been stuck on this problem for a few days and would appreciate some ideas or help in resolving it. I have a collection of objects

 public class Hierarchy
{
    public Hierarchy(string iD, string name, int level, string parentID, string topParent)
    {
        ID = iD;
        Name = name;
        Level = level;
        ParentID = parentID;
        Children = new HashSet<Hierarchy>();
    }
    public string ID { get; set; }
    public string Name{ get; set; }
    public int Level { get; set; }
    public string ParentID { get; set; }
    public ICollection<Hierarchy> Children { get; set; }
}

从Linq查询到我的实体的数据是:

The data from the Linq Query to my Entity is:

ID      Name     Level ParentID
295152  name1    1     null
12345   child1   2     295152
54321   child2   2     295152
44444   child1a  3     12345
33333   child1b  3     12345
22222   child2a  3     54321
22221   child2b  3     54321
22002   child2c  3     54321
20001   child2a2 4     22222
20101   child2b2 4     22222

此数据可能会扩展到未知的级别深度(我仅显示4). 最终,我将拥有一个带有多个子对象的集合的层次结构对象,而这些子对象又可能具有多个子对象的集合...等等... 永远只有一个顶层对象.

This data could extend to an unknown depth of levels (I'm only showing 4). Ultimately I would have one Hierarchy object with a collection of multiple child objects which in turn may have a collection of multiple child objects...etc... There will always only be one top level object.

我正在尝试在此项目中尽可能多地使用Linq.

I am trying to use Linq as much as possible in this project.

这显然需要某种递归方法,但是我被卡住了.任何想法或帮助,将不胜感激.

This obviously needs some sort of recursive method but I'm stuck. Any ideas or help would be appreciated.

TIA

推荐答案

您可以尝试以下递归函数:

You can try this recursive function:

void PopulateChildren(Hierarchy root, ICollection<Hierarchy> source)
{
    foreach (var hierarchy in source.Where(h => h.ParentID == root.ParentID))
    {
        root.Children.Add(hierarchy);
        PopulateChildren(root, source);
    }
}

您可以这样使用:

ICollection<Hierarchy> hierarchies = new List<Hierarchy>(); // source

// Get root
var root = hierarchies.Single(h => h.Level == 1);

// Populate children recursively
PopulateChildren(root, hierarchies);

这篇关于将平面集合转换为分层集合的递归方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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