将平面集合转换为层次集合的递归方法?

2024-06-18

我已经被这个问题困扰了几天,希望得到一些想法或帮助解决它。 我有一个对象集合

 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 查询到我的实体的数据是:

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 个)。 最终,我将拥有一个 Hierarchy 对象,其中包含多个子对象的集合,而这些子对象又可能拥有多个子对象的集合......等等...... 始终只有一个顶级对象。

我正在尝试在这个项目中尽可能多地使用 Linq。

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

TIA


您可以尝试这个递归函数:

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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将平面集合转换为层次集合的递归方法? 的相关文章

随机推荐