创建动态列表取决于会员

时间:2015-01-13 07:54:07

标签: c# .net winforms dictionary

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

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

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

然后是foreach项目,我用点分解它。&#39;得到他们的孩子:

e.g: 规则 - childOf - &gt; 版本 - childOf - &gt; Beta - childOf - &gt; 项目

Project.Beta.Version.Rule

中的

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

我想要做的是将每个在Dictionary中分割的String保存为Key。和valueKey是它的孩子。

继承我的班级:

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

和我的字典:

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

问题: 如何动态保存Dictionary的对象字典?

输出应该是(基于以上样本):

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>

1 个答案:

答案 0 :(得分:0)

检查我创建的这个小提琴

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