【问题标题】:Create New Dictionary On Every Button Press在每次按下按钮时创建新词典
【发布时间】:2025-11-25 10:35:01
【问题描述】:

我正在计算用户表单上起始值和结束值之间的所有数字。我的问题是,用户经常需要计算相同的值并延长起点或延长终点,这样做会引发错误

已添加具有相同密钥的项目

这是我的语法 - 我需要改变什么来消除这个错误?

public partial class Test
{
    Dictionary<int, double[]> dictionary = new Dictionary<int, double[]>();

    private void btnCalculate_Click(object sender, EventArgs e)
    {
        int start = txtStart.Text;
        int end = Convert.ToInt32(txtEnd.Text)+1;

        int[] ag = Enumerable.Range(start, end - start).ToArray();

        foreach (int a in ag)
        {
            dictionary.Add(a, new double[] { a*10, a*15, a*20 });
        }
    }
}

【问题讨论】:

  • 如果您每次按下按钮时都生成这些值,您是否考虑过先清除字典(即dictionary.Clear())? Dictionary.Add() 当键已经存在时抛出。如果您使用索引语法,则先前的值将被覆盖/替换,无一例外。
  • 字典.Clear();这么简单的解决方案!
  • 解决了吗?我可以输入它作为答案。编辑:太晚了,其他人已经进入了。

标签: c# .net dictionary c#-4.0


【解决方案1】:

确保您没有在 Dictionary 中重复使用相同的 key 两次。

Dictionary 类需要 keyvaluekey 必须始终是唯一的。 value 属性不需要是唯一的,只需 key

这是允许的:

dictionary.Add(1, new double[] {10, 12.5, 7})
dictionary.Add(2, new double[] {1, 14.5, 2})

这是不允许允许的

dictionary.Add(1, new double[] {10, 12.5, 7})
dictionary.Add(1, new double[] {1, 14.5, 2})

【讨论】:

    【解决方案2】:

    您可以清除Dictionary&lt;int, double[]&gt; 或在添加之前检查密钥是否已存在:

    public partial class Test
    {
        Dictionary<int, double[]> dictionary = new Dictionary<int, double[]>();
    
       private void btnCalculate_Click(object sender, EventArgs e)
       {
           dictionary.Clear();
    
           int start = txtStart.Text;
           int end = Convert.ToInt32(txtEnd.Text)+1;
    
           int[] ag = Enumerable.Range(start, end - start).ToArray();
    
           foreach (int a in ag)
           {
               dictionary.Add(a, new double[] { a*10, a*15, a*20 });
           }
       }
    } 
    

    或:

    public partial class Test
    {
        Dictionary<int, double[]> dictionary = new Dictionary<int, double[]>();
    
       private void btnCalculate_Click(object sender, EventArgs e)
       {
           int start = txtStart.Text;
           int end = Convert.ToInt32(txtEnd.Text)+1;
    
           int[] ag = Enumerable.Range(start, end - start).ToArray();
    
           foreach (int a in ag)
           {
               if(!dictionary.ContainsKey(a))
                   dictionary.Add(a, new double[] { a*10, a*15, a*20 });
           }
       }
    }
    

    我不确切知道您的用例是什么,但这应该可以解决您的问题

    【讨论】: