c# - 如何通过以下语法访问 C# 字典元素?

标签 c# mysql .net dictionary generics

我创建了一个列表,表示 xls 工作表中的单元格值,它看起来像这样,后面跟着一个 INSERT 语句,我将使用该语句将这些值放入某个数据库中:

List<FieldValues> fieldValues = new List<FieldValues>()
{
    new FieldValues(tableFields[0]) {
        dictionary = new Dictionary<int, string>()
        {
            {0, "" },
            {1, "" }
        }

    },
    new FieldValues(tableFields[1]) {
        dictionary = new Dictionary<int, string>()
        {
            {0, "x" },
            {1, "x" }
        }

    },
    new FieldValues(tableFields[2]) {
        dictionary = new Dictionary<int, string>()
        {
            {0, "x" },
            {1, "x" }
        }

    },
    new FieldValues(tableFields[3])  {
        dictionary = new Dictionary<int, string>()
        {
            {0, "Car" },
            {1, "Travel" }
        }

    },
};


string createQuery2 = createQuery + "\n INSERT INTO `poi_specs_mgu_ece_1.6` (";

for (var i = 0; i < tableFields.Count; i++)
{
    createQuery2 += "\n\t" + tableFields[i].GetFieldDeclaration() + (i == tableFields.Count - 1 ? string.Empty : ",");
}
createQuery2 += ")\n VALUES ( ";


for (var i = 0; i < fieldValues.Count; i++)
{

    createQuery2 += "\n\t" + fieldValues[i].dictionary; //+ (i == fieldValues.Count - 1 ? string.Empty : ",");
}
createQuery2 += " \n);";

当我创建createQuery2时,它返回(在VALUES内)以下内容:

System.Collections.Generic.Dictionary2[System.Int32,System.String] System.Collections.Generic.Dictionary2[System.Int32,System.String] System.Collections.Generic.Dictionary2[System.Int32,System.String] System.Collections.Generic.Dictionary2[System.Int32,System.String]

而不是字典中的值。 有人可以帮助我更好地想象这个问题吗?为什么我无法读取字典元素?

最佳答案

在这部分代码中:

createQuery2 += "\n\t" + fieldValues[i].dictionary;

当字典是一个对象时,您将其添加到字符串中,因此它会尝试将您的对象转换为字符串,而字符串仅返回类型。

您需要直接访问字典值。

像这样:

createQuery2 += "\n\t" + fieldValues[i].dictionary[0] + fieldValues[i].dictionary[1];

关于c# - 如何通过以下语法访问 C# 字典元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41931142/

相关文章:

c# - 实例化泛型类时如何避免指定冗余类型

c# - MySQL 连接器网络 6.9.9 设置向导提前结束

c# - C# 中的泛型方法

php - 如何准备查询以从另一个表检查然后从另一个表获取

php - MediaWiki 文本表如何连接到类别表?

c# - 在 .Net Compact Framework 中使用 X509 证书进行客户端身份验证 HTTPRequest

单击时 C# XAML 列表框折叠

mysql - 从 MySQL 表中获取顶级玩家

c# - HttpRequest 和 POST

.net - Winform 没有.NET 框架?