Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Command Result to Dictionary C# .NET 2.0

Tags:

c#

sql

.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 that stuff. I feel like this must be a common problem but I haven't found any good solutions.

Thanks in advance.

like image 729
Joel Avatar asked Mar 29 '10 15:03

Joel


3 Answers

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.

like image 128
Ahmad Mageed Avatar answered Nov 06 '22 11:11

Ahmad Mageed


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"]);
}
like image 15
Gabe Moothart Avatar answered Nov 06 '22 11:11

Gabe Moothart


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())           
}
like image 1
wonde Avatar answered Nov 06 '22 11:11

wonde