C# - 从数据库中检索数据并存储在二维字典中?

标签 c# asp.net database linq dictionary

你好,我尝试做一些类似 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:“字典中不存在给定的键。”

我该怎么办?

最佳答案

问题是你必须初始化每个内部 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;
}

关于C# - 从数据库中检索数据并存储在二维字典中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46260082/

相关文章:

c# - 为什么 DateTimePicker 在 Leave 事件处理程序中返回过时的值?

c# - LoadLibrary、FreeLibrary 和 GetModuleHandle Win32 函数线程安全吗?

asp.net - 如何在占位符中动态生成的标签之间创建换行符?

c# - 如何在 ASP .NET 中的 Web 窗体控件中实现 CSS 类?

mysql - 错误 : column specified more than once in Postgres

c# - ASP.NET 核心 : Preserve ForeignKey Relation in JsonResult

c# - C# 动态创建对象数组

c# - 在 Entity Framework 中更改命名空间

c# - C#中如何检查记录是否存在

sql - 如何在H2中将时间转换为24小时格式