首页 > 解决方案 > 如何在 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 数据库

这可能吗??

标签: c#sql-serverdictionarykeyvaluepair

解决方案


您可以使用任何 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));
            }                   
        }
    }
}

推荐阅读