簡體   English   中英

遞歸使用C#與父子關系構建樹

[英]Building a tree with parent child relationship using c# recursively

我有一個要轉換為樹形結構的列表。 如何將其轉換為樹結構?

通過遞歸檢查父子關系C#線程來查看“構建樹類型”列表,但是由於類中的鍵是字符串,因此無法使用該解決方案。 請幫忙

internal class Program
{
        private static void Main(string[] args)
        {
            List<node> nodeList = new List<node>();
            node n = new node("A", "A1", null, 1); nodeList.Add(n);
            n = new node("B", "A2", "A1", 2); nodeList.Add(n);
            n = new node("C", "A3", "A1", 2); nodeList.Add(n);
            n = new node("D", "A4", "A1", 2); nodeList.Add(n);

            n = new node("E", "A5", "A2", 3); nodeList.Add(n);
            n = new node("F", "A6", "A5", 4); nodeList.Add(n);
            n = new node("G", "A7", "A3", 3); nodeList.Add(n);
            n = new node("H", "A8", "A4", 3); nodeList.Add(n);
            n = new node("I", "A9", "A4", 3); nodeList.Add(n);
            n = new node("J", "A10", "A4", 3); nodeList.Add(n);
            n = new node("K", "A11", "A10", 4); nodeList.Add(n);
            n = new node("L", "A12", "A10", 4); nodeList.Add(n);
            n = new node("M", "A13", "A12", 5); nodeList.Add(n);
            n = new node("N", "A14", "A12", 5); nodeList.Add(n);
            n = new node("O", "A15", "A10", 4); nodeList.Add(n);

            n = new node("P", "A16", null, 1); nodeList.Add(n);
            n = new node("Q", "A17", "A16", 2); nodeList.Add(n);
        }
}

public class node
{
        public string name { get; set; }
        public string key { get; set; }
        public string parentKey { get; set; } 
        public int level { get; set; }

        public List<node> Children { get; set; }

        public node(string Name, string Key, string PK, int Level)
        {
            name = Name;
            key = Key;
            parentKey = PK;
            level = Level;
        }
}

將父ID從int更改為string的重構非常簡單

public static class GroupEnumerable {

    public static IList<node> BuildTree(this IEnumerable<node> source)
    {
        var groups = source.GroupBy(i => i.parentKey);

        var roots = groups.FirstOrDefault(g => g.Key==null).ToList();

        if (roots.Count > 0)
        {
            var dict = groups.Where(g => g.Key!=null).ToDictionary(g => g.Key, g => g.ToList());
            for (int i = 0; i < roots.Count; i++)
                AddChildren(roots[i], dict);
        }

        return roots;
    }

    private static void AddChildren(node node, IDictionary<string, List<node>> source)
    {
        if (source.ContainsKey(node.key))
        {
            node.Children = source[node.key];
            for (int i = 0; i < node.Children.Count; i++)
                AddChildren(node.Children[i], source);
        }
        else
        {
            node.Children = new List<node>();
        }
    } 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM