.net 将具有层次结构的词典转换为列表
我有一个具有层次结构的基本dictionary对象,其中键是子对象,对是其父对象 下面是字典中键值对的示例数据.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<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,