2015-10-17 75 views
1

我有一個帶有層次結構的基本字典對象,其中KEY是子對象,PAIR是其父對象。將具有層級結構的字典轉換爲列表

以下是字典中鍵值對的示例數據。

Dictionary<string,string> elements; 

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

我想將此字典轉換爲List<string>,保持元素的層次順序。所以,輸出將如下所示:

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

這怎麼辦?預先感謝您的建議。

回答

2

首先,我們可以通過檢查字典中的值集合中是否存在這樣的鍵來找到第一個鍵。然後我們就可以把它添加到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,