gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:56:18 24 4
gpt4 key购买 nike

你好,我尝试做一些类似 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com