27

I have a table with 2 columns defined as varchar(50): Column1 and Column2. I want to return a dictionary of <string, string> where each row is in the dictionary and where Column1 is the key and Column2 is the value. This is what I have:

public Dictionary<string, string> LoadAllTheDataFromDB()
{
   using (MyDC TheDC = new MyDC())
   {
       return (from c in TheTable
               select new Dictionary<string, string>()
               {
                     //stuck here

               }).FirstOrDefault();

   }
}

How do I make it that the dictionary is filled?

1
  • First Select those two columns (new {c.Column1, c.Column2}), then materialize (ToArray), then call ToDictionary. Commented Nov 19, 2016 at 22:03

2 Answers 2

61

Try this:

var dict = TheTable.Select( t => new { t.Col1, t.Col2} )
               .ToDictionary( t => t.Col1, t => t);

Remember in select lambda you will perform projection and create some anonymous object. Then in ToDictionary you will pass two parameters: First Parameter is a lambda to specify the key; in code above we are choosing Col1 to be the key. Second parameter is a lambda to specify the value; in code above we are choosing the object itself to be the value.

If you want the value to be an anonymous type, change the 2nd lambda like this:

ToDictionary( t => t.Col1, t => new { t.Col2 });

If you want the value to be a type you have defined, change the 2nd lambda like this:

ToDictionary( t => t.Col1, t => new YourType { Prop1 = t.Col2 });
Sign up to request clarification or add additional context in comments.

1 Comment

Please, do not forget to mark the answer you perceive as correct.
3

Since you just need value of one first row why not to do that first:

 var row = TheTable.FirstOrDefault();

And than just construct that dictionary if you got the result:

 return row == null ? null : 
       new Dictionary<string,string>{ {row.Column1, row.Column2 } }; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.