how to convert Dictionary<dynamic, dynamic> to Dictionary<string, string> using Colllection.ToDictionary()
Asked Answered
L

2

8

I am using Dapper to fetch a 2 column resultset into a dictionary. I noticed that intellisense shows me a .ToDictionary() when I hover over the resultset but I cannot get it to work since dapper uses dynamic properties/expandoObject

Dictionary<string, string > rowsFromTableDict = new Dictionary<string, string>();
using (var connection = new SqlConnection(ConnectionString))
{
   connection.Open();
   var results =  connection.Query
                  ("SELECT col1 AS StudentID, col2 AS Studentname 
                    FROM Student order by StudentID");
    if (results != null)
    {
    //how to eliminate below foreach using results.ToDictionary()
    //Note that this is results<dynamic, dynamic>
         foreach (var row in results)
         {
              rowsFromTableDict.Add(row.StudentID, row.StudentName);
         }
         return rowsFromTableDict;
     }
}

thank you

Luthern answered 19/10, 2011 at 17:29 Comment(0)
K
14

Try:

results.ToDictionary(row => (string)row.StudentID, row => (string)row.StudentName);

Once you have a dynamic object, every thing you do with it and the corresponding properties and methods are of the dynamic type. You need to define an explicit cast to get it back into a type that is not dynamic.

Kasi answered 19/10, 2011 at 19:1 Comment(1)
Dynamic is nice, but it does have a lot of traps like needing casts back to static types.Kasi
G
-1
if (results != null)
{
    return results.ToDictionary(x => x.StudentID, x => x.StudentName);     
}
Grady answered 19/10, 2011 at 17:31 Comment(1)
I knew this was not that simple. Error 1 Cannot implicitly convert type 'System.Collections.Generic.Dictionary<dynamic,dynamic>' to 'System.Collections.Generic.Dictionary<string,string>'Luthern

© 2022 - 2024 — McMap. All rights reserved.