如何使用Colllection.ToDictionary()将Dictionary <dynamic,dynamic>转换为Dictionary <string,string>

Gul*_*llu 8 c# expando expandoobject c#-4.0 dapper

我正在使用Dapper将2列结果集提取到字典中.我注意到当我将鼠标悬停在结果集上时,intellisense向我显示了一个.ToDictionary(),但由于dapper使用动态属性/ 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;
     }
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Jos*_*ers 14

尝试:

results.ToDictionary(row => (string)row.StudentID, row => (string)row.StudentName);
Run Code Online (Sandbox Code Playgroud)

拥有动态对象后,您使用它做的每件事以及相应的属性和方法都属于动态类型.您需要定义一个显式转换以将其恢复为非动态类型.