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

编程入门 行业动态 更新时间:2024-10-14 10:39:41
本文介绍了将平面集合转换为分层集合的递归方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

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

本文发布于:2023-11-30 03:41:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648602.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   转换为   平面   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!