Search code examples
c#.netvb.netlistdata-dictionary

Read SQL Table into Dictionary<string, List<string[]>>


I have a SQL table that looks like this:

AAA, Amanda, Anthony
AAA, Anna, Andrew
BBB, Boris, Benji
BBB, Blondie, Bobby

I'm trying to use a SQL data reader to read the data then insert the results into a Dictionary<string, List<string[]>>

The expected result is:

[Key]
   "AAA"
[Value]
   "Amanda", "Anthony"
   "Anna", "Andrew"
[Key]
   "BBB"
[Value]
   "Boris", "Benji"
   "Blondie", "Bobby"

Please help:

using (SqlConnection cnn = new SqlConnection("connection"))
{
   using (SqlCommand cmd = new SqlCommand("command", cnn))
   {
      using (SqlDataReader rdr = cmd.ExecuteReader())
      {
         while (rdr.Read())
            {
               ... ?
            }
      {
   {
}

Solution

  • Something similar to this:

     var dict = new Dictionary<string, List<string[]>>();
     while (rdr.Read())
     {
         // TODO: extract field1, field2, field3
         if(dict.ContainsKey(field1))
         {
             // Add the values to the existing list
             dict[field1].Add(new string [] {field2 , field3});
         }
         else
         {
             //Create a new list and set the initial value
             dict[field1] = new List<string[]> { new string[] { field2 , field3 } };
         }
     }