字典C#.NET 2.0的SQL命令结果 [英] SQL Command Result to Dictionary C# .NET 2.0

查看:74
本文介绍了字典C#.NET 2.0的SQL命令结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在.NET 2.0中有一个简单的SQL查询(使用SqlCommand,SqlTransaction),该查询返回一个整数字符串对(ID,名称)表。我想将这些数据放入像 Dictionary< int,string> 这样的字典中。

I have a simple SQL query (using SqlCommand, SqlTransaction) in .NET 2.0 that returns a table of integer-string pairs (ID, Name). I want to get this data into a dictionary like Dictionary<int, string>.

我可以得到结果到DataTable中,但是即使对其进行迭代,我也不知道如何进行输入以及所有这些工作。我觉得这肯定是一个普遍的问题,但是我没有找到任何好的解决方案。

I can get the result into a DataTable, but even iterating over it, I'm not sure how to do the typing and all that stuff. I feel like this must be a common problem but I haven't found any good solutions.

预先感谢。

推荐答案

您可以尝试类似的方法,将其调整为适合当前循环结果的方法:

You could try an approach similar to this, adjusted to however you're currently looping over your results:

Dictionary<int, string> dictionary = new Dictionary<int, string>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    using (SqlCommand command = new SqlCommand(queryString, connection))
    {
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                dictionary.Add(reader.GetInt32(0), reader.GetString(1));
            }
        }
    }
}

// do something with dictionary

SqlDataReader.GetInt32方法 SqlDataReader.GetString方法分别代表 ID Name 列索引。

The SqlDataReader.GetInt32 method and SqlDataReader.GetString method would represent the ID and Name column indices, respectively.

这篇关于字典C#.NET 2.0的SQL命令结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆