【问题标题】:How can I acces c# dictionary elements from the below syntax?如何从以下语法访问 c# 字典元素?
【发布时间】:2017-01-30 07:55:07
【问题描述】:

我创建了一个表示 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]

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

【问题讨论】:

  • fieldValues[i].dictionary 是一个字典,你只是它的 ToString,如果你使用 fieldValues[i].dictionary[0] 你会得到价值。但是:您的代码对 sql 注入是开放的,使用参数而不是仅仅连接值!
  • 你能解释一下字典的两个键分别代表什么吗?它们是字段的名称和值吗?

标签: c# mysql .net dictionary generics


【解决方案1】:

在这部分代码中:

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

当它是一个对象时,你正在将字典添加到一个字符串中,所以它会尝试将你的对象变成一个字符串,它只返回类型。

您需要直接访问字典值。

像这样:

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

【讨论】:

  • 但是,假设我想创建一个方法来检查字典是否有特定的行?像这样 new FieldValues(tableFields[3]) { dictionary = new Dictionary() { {0, "Car" }, {1, "Travel" } } 如何访问字典行
  • 对不起,您可以忽略我的最后一条评论:本来应该是 但是,假设我想创建一个方法来检查字典是否有特定的行?像这样的东西 public string GetRowValue(int row) { return string.Empty; } 我如何才能访问以验证我的字典是否有特定的行?
  • 如果我对您的理解正确,您应该能够内联调用您的新 GetRowValue(int row) 方法,而不是 fieldValues[i].dictionary[row]。也就是说,听起来可能有更好的方法来做你正在尝试的事情。如果您编辑问题以提供有关您想要完成的任务的更多详细信息,也许人们可以帮助您提出更好的解决方案。
  • 主要思想是我想检查某行是否存在,具体取决于我定义的类型:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
  • 2018-07-05
  • 1970-01-01
  • 1970-01-01
  • 2013-03-24
  • 2011-07-21
相关资源
最近更新 更多