簡體   English   中英

C#-從數據庫中檢索數據並存儲在二維字典中?

[英]C# - Retrieve data from Database and store in 2 dimension dictionary?

您好,我嘗試執行類似PHP的操作,即從數據庫中檢索數據並將其存儲在2維集合(字典)中,我不確定是否正確編寫了它。

假設我的數據庫表和預期的結構結果如下所示(請參見屏幕截圖)

點擊查看截圖

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: '字典中不存在給定的鍵。

我該怎么辦?

字典是二維的。 初始化時

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;
}

問題是,在為外部詞典分配新鍵時Dictionary<string, 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>();
      }

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM