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



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

谢谢

尝试:

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

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

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

相关内容

  • 没有找到相关文章