frenchie frenchie - 20 days ago 5
ASP.NET (C#) Question

Returning a Dictionary<string, string> from a linq query

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?

Thanks.

Answer

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 choose one property of the anonymous to be your key and the object itself to be the value.