Read SQL Table into Dictionary<string, List<string[]>>
-
13-07-2021 - |
Question
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 } };
}
}
OTHER TIPS
This is pretty simple, I think. Read through your data table, and for each row, check to see if [key] exists in your dictionary. If not, add it with a new List containing your [value]; otherwise, add the [value] to the List at position [key].
If you sort the data table, you can speed this up using a classic control break technique -- for each new [key], start accumulating a List until the [key] changes, then add the [key] and List to your dictionary.
while (rdr.Read())
{
if (dictionary.ContainsKey((string)rdr["column1"]){
dictionary[(string)rdr["column1"]].Value.Add(new string[]{(string)rdr["column2"], (string)rdr["column3"]});
} else {
dictionary.Add((string)rdr["column1"]), new List<string>());
dictionary[(string)rdr["column1"]].Value.Add(new string[]{(string)rdr["column2"], (string)rdr["column3"]});
}
}
This should work.
Something like this maybe?
myDict.Add(rdr["key"].ToString(), rdr["value"].ToString().Split(",").ToList());
Untested, but it should get you going in the right direction...