【问题标题】:how to convert Dictionary<dynamic, dynamic> to Dictionary<string, string> using Colllection.ToDictionary()如何使用 Colllection.ToDictionary() 将 Dictionary<dynamic, dynamic> 转换为 Dictionary<string, string>
【发布时间】:2011-10-19 17:29:04
【问题描述】:

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

谢谢

【问题讨论】:

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


    【解决方案1】:

    试试:

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

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

    【讨论】:

    • 动态很好,但它确实有很多陷阱,比如需要强制转换回静态类型。
    【解决方案2】:
    if (results != null)
    {
        return results.ToDictionary(x => x.StudentID, x => x.StudentName);     
    }
    

    【讨论】:

    • 我知道这不是那么简单。错误 1 ​​无法将类型 'System.Collections.Generic.Dictionary' 隐式转换为 'System.Collections.Generic.Dictionary'
    猜你喜欢
    • 1970-01-01
    • 2019-09-14
    • 2014-10-22
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    相关资源
    最近更新 更多