dahui dahui -3 years ago 150
C# Question

Convert SQL query result to C# Dictionary in LINQPad

Let's say I have the following data in an SQL table:

ID A1 A2
0 1 abc
1 2 def
2 1 ghi


I have a query:

SELECT ID, A2 FROM MyTable WHERE A1 = 1


This will return two records, IDs 0 and 2.

I'd like to run this query in LINQpad, and return the results as a Dictionary collection. Obviously the key will be ID, and the value will be the value of A2.

LINQpad is connected up to the DB with the "Connection" dropdown in the top right. I am in "C# Program" mode, I think this is causing issues as every example I've tried seem to be in statements or expression mode. I want to get it working in Program mode though so I can run this from other Programs.

Answer Source

First you need to add a connection to your database in the LINQPad dropdown. If your table is called MyTable this will give you access to a LINQPad object called MyTables. Now the following code (in LINQPad C# Program Mode) should return a Dictionary Object:

void Main()
{

    var result = MyTables
                .Where(mc => mc.A1 == 1)
                .ToDictionary(m => m.ID.ToString(), 
                              m => m.A2.ToString());
    result.Dump();
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download