【问题标题】:Converting a Dictionary with a hierarchical structure into a List将具有层次结构的字典转换为列表
【发布时间】:2016-01-16 07:33:49
【问题描述】:

我有一个具有层次结构的基本字典对象,其中 KEY 是子对象,PAIR 是其父对象。

这是字典中键值对的示例数据。

Dictionary<string,string> elements;

("Cell", "Cells")
("Cells", "Tissue")
("Tissue", "Organ")
("Organ", "System")
("System", "Body")

我想将此字典转换为List&lt;string&gt;,保持元素的层次顺序。因此,输出将如下所示:

"Cell",
"Cells",
"Tissue",
"Organ",
"System", 
"Body"

如何做到这一点?提前感谢您的建议。

【问题讨论】:

    标签: .net c#-4.0 dictionary collections


    【解决方案1】:

    首先,我们可以通过检查字典内的值集合中不存在这样的键来找到第一个键。然后我们可以将它添加到List 并通过使用我们的List 集合中的最后一个键访问我们字典中的值来添加所有其他键(这有助于我们保持正确的顺序):

            Dictionary<string, string> elements = new Dictionary<string, string>()
            {
                {"Tissue", "Organ"},
                {"Cell", "Cells"},
                {"System", "Body"},
                {"Cells", "Tissue"},
                {"Organ", "System"},
            };
    
            List<string> hierarchy = new List<string>();
    
            hierarchy.Add(elements.Keys.First(el => !elements.ContainsValue(el)));
    
            while(elements.ContainsKey(hierarchy.Last()))
                hierarchy.Add(elements[hierarchy.Last()]);
    
            foreach (var item in hierarchy)
                Console.Write(item + ",  ");
    
            Console.ReadKey();
    

    输出:

    Cell, Cells, Tissue, Organ, System,  Body,
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多