我创建了一个列表,表示 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.Dictionary
2[System.Int32,System.String] System.Collections.Generic.Dictionary
2[System.Int32,System.String] System.Collections.Generic.Dictionary2[System.Int32,System.String] System.Collections.Generic.Dictionary
2[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/