我正在对用户表单上的起始值和结束值之间的所有数字执行计算。我的问题是,用户通常需要计算相同的值并延长开始时间或扩展结束点,这样做会引发错误
已添加具有相同键的项目
这是我的语法 - 我需要更改哪些内容才能删除此错误?
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 });
}
}
}
答案 0 :(得分:3)
您可以清除Dictionary<int, double[]>
或在添加之前检查密钥是否已存在:
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 });
}
}
}
我不确切知道您的用例是什么,但这应该可以解决您的问题
答案 1 :(得分:0)
确保您没有在key
中重复使用相同的Dictionary
两次。
Dictionary
课程需要key
和value
,而key
必须始终是唯一的。 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})