SQL Command Result to Dictionary C# .NET 2.0
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 t开发者_开发百科hat 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())
}
IDictionary<int, string> dict = new Dictionary<int, string>();
DataTable mydata = new DataTable("hey");
foreach (DataRow item in mydata.Rows)
{
dict.Add(item["id"], item["name"]);
}
i did not type this in visual studio so you might need to make minor changes to make it run...
Dictionary(int key,string value) dictionary = new Dictionary<int key,string value>();
foreach(DataRow row in DataTable.Rows)
{
//null check??
dictionary.add(Convert.toInt(row[0]),row[1].toString());
}
try that ... see if that helps.
精彩评论