Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 将具有层次结构的词典转换为列表_.net_C# 4.0_Dictionary_Collections - Fatal编程技术网

.net 将具有层次结构的词典转换为列表

.net 将具有层次结构的词典转换为列表,.net,c#-4.0,dictionary,collections,.net,C# 4.0,Dictionary,Collections,我有一个具有层次结构的基本dictionary对象,其中键是子对象,对是其父对象 下面是字典中键值对的示例数据 Dictionary<string,string> elements; ("Cell", "Cells") ("Cells", "Tissue") ("Tissue", "Organ") ("Organ", "System") ("System", "Body") 你怎么能做到这一点?提前感谢您的建议。首先,我们可以通过检查字典内的值集合中是否不存在第一个键来找到第一个

我有一个具有层次结构的基本dictionary对象,其中键是子对象,对是其父对象

下面是字典中键值对的示例数据

Dictionary<string,string> elements;

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

你怎么能做到这一点?提前感谢您的建议。

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

"Cell",
"Cells",
"Tissue",
"Organ",
"System", 
"Body"
        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,