字典C#.NET 2.0的SQL命令结果 [英] SQL Command Result to Dictionary C# .NET 2.0
问题描述
我在.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屋!