根据成员创建动态列表

Create Dynamic List Depends on Member

我需要一些在字典下保存字典的动态逻辑

我有这个单独的字符串列表:

List<string> lstString = new List<string>();
    lstString.Add("Project.Beta.Version.Rule");
    lstString.Add("Project.Program.Table");
    lstString.Add("Project.Program");
    lstString.Add("Zip.File");

然后对于每个项目,我用点 '.' 将其拆分得到他们的 child:

例如: 规则--child的-->版本-- childOf--> Beta --childOf--> 项目

Project.Beta.Version.Rule

foreach(var item in lstString)
{
   string[] strSpl = item.Split('.');
}

我想做的是将每个拆分为 Dictionary 的 String 保存为 Key 。 valueKey 是它的 child .

这是我的 class :

class RfClass
{
   public Dictionary<string, RfClass> lstRefClass = new Dictionary<string, RfClass>();
}

和我的字典:

public Dictionary<string, RfClass> lstRefClass = new Dictionary<string, RfClass>();

问题: 如何动态保存字典的 Object 字典?

输出应该是(基于上面的示例):

Dictionary:
   Key: Project
   Value: Dictionary<string, RfClass>
          Key: Beta
          Value: Dictionary<string, RfClass>
                 Key: Version
                 Value: Dictionary<string, RfClass>
                        Key: Rule
                        Value: Dictionary<string, RfClass>
          Key: Program
          Value: Dictionary<string, RfClass>
                 Key: Table
                 Value: Dictionary<string, RfClass>
   Key: Zip
   Value Dictionary<string, RfClass>
         Key: File
         Value: Dictionary<string, RfClass>

检查我创建的 fiddle

https://dotnetfiddle.net/W54ImW

我想应该对你有帮助

示例的完整代码

using System;
using System.Collections.Generic;

public class Program
{
public static void Main()
{

    List<string> lstString = new List<string>();
    lstString.Add("Project.Beta.Version.Rule");     
    lstString.Add("Project.Program.Table");
    lstString.Add("Project.Program");
    lstString.Add("Zip.File");

    var root = new RfClass();

    foreach(var x in lstString)
    {
        string[] words = x.Split('.');
        CreateTree(root, words, 0);
    }

    Display(root);
}   

public static void CreateTree(RfClass root, string[] words, int idx)
{
    RfClass next;
    if (false == root.lstRefClass.TryGetValue(words[idx], out next))
    {
        next = new RfClass();
        root.lstRefClass.Add(words[idx], next);
    }
    if (idx + 1 < words.Length)
        CreateTree(next, words, idx + 1);
}

public static void Display(RfClass root, int indent = 0)
{
    foreach(var p in root.lstRefClass)
    {
        Console.WriteLine("{0} key: {1} ",new string('\t', indent), p.Key);
        Console.WriteLine("{0} Value: Dictionary<string, RfClass>", new string('\t', indent));
        Display(p.Value, indent+1);
    }
}

public class RfClass
{
   public Dictionary<string, RfClass> lstRefClass = new Dictionary<string, RfClass>();
}
}