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

8

我正在使用Dapper将一个2列结果集提取到一个字典中。

我注意到当我将鼠标悬停在结果集上时,智能提示会显示.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个回答

14

尝试:

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

如果你有一个动态对象,那么对它进行的所有操作、以及相关的属性和方法都属于动态类型。你需要定义一个显式转换来将它转换回非动态类型。


动态很好,但它确实有很多陷阱,比如需要将类型强制转换回静态类型。 - Joshua Rodgers

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

我知道这不是那么简单的。错误1:无法隐式转换类型'System.Collections.Generic.Dictionary<dynamic,dynamic>'为'System.Collections.Generic.Dictionary<string,string>'。 - Gullu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接