如何转换Dictionary到字典

本文关键字:dynamic string 字典 使用 ToD Colllection 转换 Dictionary 何转换 | 更新日期: 2023-09-27 18:11:39

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

谢谢

如何转换Dictionary<dynamic, dynamic>到字典<string;使用Colllection.ToD

尝试:

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

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

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