【问题标题】:C# - Retrieve data from Database and store in 2 dimension dictionary?C# - 从数据库中检索数据并存储在二维字典中?
【发布时间】:2018-02-25 20:33:46
【问题描述】:

您好,我尝试做类似 PHP 的事情,即从数据库中检索数据并存储在二维集合(字典)中 我不确定我写的是否正确。

假设我的数据库表和预期的结构结果如下所示(见截图)

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:'给定的键不在字典中。'

我该怎么办?

【问题讨论】:

    标签: c# asp.net database linq dictionary


    【解决方案1】:

    问题是在为外部字典分配新键时,您必须初始化每个内部 Dictionary&lt;string, string&gt;。通常这意味着检查此键是否存在,如果不存在,则创建对象:

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

    【讨论】:

      【解决方案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;
      }
      

      【讨论】:

      • 很好的答案先生
      猜你喜欢
      • 2015-04-26
      • 1970-01-01
      • 1970-01-01
      • 2013-06-06
      • 2020-12-11
      • 1970-01-01
      • 2017-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多