gpt4 book ai didi

c# - 如何使用 Colllection.ToDictionary() 将 Dictionary 转换为 Dictionary

转载 作者:太空狗 更新时间:2023-10-29 18:20:39 26 4
gpt4 key购买 nike

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

谢谢

最佳答案

尝试:

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

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

关于c# - 如何使用 Colllection.ToDictionary() 将 Dictionary<dynamic, dynamic> 转换为 Dictionary<string, string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7825438/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com