2017-09-17 136 views
1

你好,我嘗試做類似PHP這是從數據庫中檢索數據和存儲在二維集合(字典)的東西 我不知道我寫的是否正確。C# - 從數據庫中檢索數據並存儲在2維字典中?

比方說,我的數據庫表和預期結構的結果是這樣的(見截圖)

Click to see screenshot

public ActionResult ShowBook() 
{   
     var books = from v in db.Books 
         select v; 

     Dictionary<string, Dictionary<string, string>> test = new Dictionary<string, Dictionary<string, string>>(); 
     foreach (var item in books) 
     { 

      test[item.Book_Type_ID][item.Author_ID] = item.Book_Name; 
     } 

     return ..... 

} 

但我有這個錯誤

System.Collections.Generic.KeyNotFoundException:「給定的鍵不存在在字典裏。'

我該怎麼辦?

回答

2

字典是二維的。當你初始化

Dictionary<string, Dictionary<string, string>> test = new Dictionary<string, Dictionary<string, string>>(); 

第一個維度被初始化,而不是第二個 - 即test是一個空的字典。因此,當您嘗試將圖書標題添加到第二維字典時,目前還沒有字典可供添加。首先,您需要檢查此條件,並創建一個條目,如果它不存在:

var books = from v in db.Books select v; 

Dictionary<string, Dictionary<string, string>> test = new Dictionary<string, Dictionary<string, string>>(); 
foreach (var item in books) 
{ 
    if (!test.ContainsKey(item.Book_Type_ID)) 
     test[item.Book_Type_ID] = new Dictionary<string, string>(); 

    test[item.Book_Type_ID][item.Author_ID] = item.Book_Name; 
} 
+0

大先生回答 – Jonesopolis

2

的問題是你必須分配一個新的關鍵是你的外部字典時初始化每個內部Dictionary<string, string>。通常,這意味着檢查,如果該鍵存在,如果沒有,創建對象:

foreach (var item in books) 
{ 
     if(!test.ContainsKey(item.Book_Type_ID)) 
     { 
      test[item.Book_Type_ID] = new Dictionary<string, string>(); 
     } 

     //now we are sure it exists, add it  
     test[item.Book_Type_ID][item.Author_ID] = item.Book_Name; 
}