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
You could try an approach similar to this, adjusted to however you're currently looping over your results:
Dictionary dictionary = new Dictionary();
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
The SqlDataReader.GetInt32 method and SqlDataReader.GetString method would represent the ID
and Name
column indices, respectively.