你好,我尝试做一些类似 PHP 的事情,即从数据库中检索数据并将其存储在二维集合(字典)中 我不确定我写的对不对。
假设我的数据库表和预期的结构结果如下所示(参见屏幕截图)
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/