【问题标题】:C# dictionary keeps changing the values into the last added value. [closed]C# 字典不断将值更改为最后添加的值。 [关闭]
【发布时间】:2016-02-03 21:07:46
【问题描述】:

当我尝试将文本框中的新名称和数字添加到字典中,然后尝试将字典的内容添加到 listBox 中时,所有先前的条目都是相同的。就像我添加“Bob Johnson 42”、“Jim Smith 33”、“Peter White 21”一样。当我把它放在 ListBox 中时,它会显示为: 彼得怀特 21 彼得怀特 21 彼得怀特 21

我做错了什么? 这是代码。

private void button1_Click(object sender, EventArgs e)
    {
           String name = this.textBox1.Text;
           int testNumber = int.Parse(textBox2.Text);
           submittedTests.Add(this.textBox1.Text, testNumber);

        foreach (var x in submittedTests)
        {
            listBox1.Items.Add(name + " " + testNumber);
        }

   }

【问题讨论】:

  • 您需要从您的字典中访问KeyValue,目前您正在访问您的局部变量。 listBox1.Items.Add(x.Key + " " + x.Value); 应该修复它

标签: c# dictionary visual-studio-2015


【解决方案1】:

您正在循环外部使用 nametestnumber 的值

   foreach (var x in submittedTests)
    {
        listBox1.Items.Add(name + " " + testNumber);
    }

应该是

   foreach (var x in submittedTests)
    {
        listBox1.Items.Add(x.name + " " + x.testNumber);
    }

或者如果submittedTests 是字典:

foreach (var x in submittedTests)
{
    listBox1.Items.Add(x.Key + " " + x.Value);
}

【讨论】:

  • 应该是x.Keyx.Value,因为它是字典。
【解决方案2】:
private void button1_Click(object sender, EventArgs e)
{
       String name = this.textBox1.Text;
       int testNumber = int.Parse(textBox2.Text);
       submittedTests.Add(this.textBox1.Text, testNumber);

    foreach (var x in submittedTests)
    {
        listBox1.Items.Add(x.Key + " " + x.Value);
    }
}

【讨论】:

    【解决方案3】:

    改变

    listBox1.Items.Add(name + " " + testNumber);
    

    listBox1.Items.Add(x.Key + " " + x.Value);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-23
      • 1970-01-01
      • 2020-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多