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>
.
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.
Thanks in advance.
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
The SqlDataReader.GetInt32 method and SqlDataReader.GetString method would represent the ID
and Name
column indices, respectively.
You can return it as a DataReader, and construct the dictionary using linq:
Dictionary<int, string> dictionary;
using (SqlCommand command = new SqlCommand(queryString, connection))
using (SqlDataReader reader = command.ExecuteReader()) {
dictionary = reader.Cast<DbDataRecord>()
.ToDictionary(row => (int)row["id"], row => (string)row["name"]);
}
You can do like this.
// Define your Dictionary
IDictionary<int,string> dictionary = new Dictionary<int,string>();
// Read your dataTable
foreach(DataRow row in dataTable.Rows) {
// Add Id and Name respectively
dictionary.Add(int.parse(row[0].ToString()),row[1].ToString())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With