C# Populate dictionary directly from SqlDataReader

c#, dictionary, sql-server, sqldatareader

Solution

You can just loop through the rows returned by the reader:

var customerLookup = new Dictionary<string, string>();
using (var reader = myLookup.ExecuteReader())
{
    while (reader.Read())
    {
        customerLookup[(string)reader["code"]] = (string)reader["customerText"];
    }
}

You should be aware that if there are any duplicate codes, subsequent code values will overwrite previous ones in the dictionary. You can use `customerLookup.Add()` instead if you'd rather an exception be thrown in such a case.

Problem

In a program that I've been working on, there are three steps to get the data into a Dictionary that's been created: - execute the SQL command - pull those results into a `DataTable`, then - pull the `DataTable` into the `Dictionary` Code: ``` var myDr = myLookup.ExecuteReader(); dt.Load(myDr); customerLookup = dt.AsEnumerable() .ToDictionary(key => key.Field<string>("code"), value => value.Field<string>("customerText")); ``` My question is, is it possible to “cut out the middleman,” so to speak, and pull the data from the `SqlDataReater` directly into the Dictionaries? Or is it necessary to pull it into a `DataTable` first? If what I'm looking to do is possible, can someone please post code for me to try? Thanks very much!

Original source