c# - 如何在 C# 中从数据库中检索 KeyValuePair 的值?
问题描述
我正在做一个涉及 KeyValuePair 的项目。我将 int 作为键,将字符串作为值。
我想要的是我想从 KeyValuePair 中获取值。
我有这个代码:
var list = new List<KeyValuePair<int, string>>()
{
new KeyValuePair<int, string>(obj,_Obj.Questions)
};
Dictionary<int, string> d = new Dictionary<int, string>
{
{ 1, "Welcome, How are you?" },
{ 2, "Tell me something about yourself."},
{ 3, "How much experience do you have?"},
};
因此,如果您在 KVP 中看到字符串 Values,例如“Welcome, How are you?”、“Tell me some about yourself”等,则是静态的。所有这些值都已经存在于我的本地数据库中。我只想要数据库中的这些字符串值。
我正在使用MS SQL 数据库
这可能吗??
解决方案
您可以使用任何 ORM,例如 Entity Framework,但是,我将提供一个手动操作的示例:
var list = new List<KeyValuePair<int, string>>()
using(var connection = new SqlConnection(connectionString))
using(var command = new SqlCommand("SELECT * FROM interview_Table", connection))
using(var reader = command.ExecuteReader())
{
if (connection.State != ConnectionState.Open) { connection.Open(); }
if (reader.HasRows)
{
foreach (var row in reader)
{
//ensurance
var isValidId = int.TryParse(row["Id"]?.ToString(), int out id);
var description = row["Description"]?.ToString();
// only fetch rows with a valid id number with description that is not empty or null
if(isValidId && !string.IsNullOrEmpty(description))
{
list.Add(new KeyValuePair<int, string>(id, description));
}
}
}
}
推荐阅读
- python - 在 vscode 中调试 python “包命令”
- nosql - 有没有办法索引 Oracle NoSQL 数据库中记录数组中的所有项目?
- php - 以两种不同的路径上传图片 Codeigniter
- c# - 设计者必须创建一个“EasyTabs.TitleBarTabs”类型的实例,但它不能,因为该类型被声明为抽象
- python - Django密码重置表单随机预填充电子邮件字段
- google-sheets - 谷歌表格:显示一周中某一天即将到来的日期
- python - 安装 autopy 时出现“SyntaxError: invalid syntax”
- nginx - 在从 https 到 http 的代理后面时强制使用 wss://
- python - 如何根据数据框标准制作脚本选择链接
- windows - 如何搜索/删除多个子文件夹?