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

时间:2011-10-19 17:29:04

标签: c# c#-4.0 dapper expando expandoobject

我正在使用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;
     }
}

谢谢

2 个答案:

答案 0 :(得分:14)

尝试:

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

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

答案 1 :(得分:-1)

if (results != null)
{
    return results.ToDictionary(x => x.StudentID, x => x.StudentName);     
}