【问题标题】:c# dictionary automatically break the for loop,c#字典自动打破for循环,
【发布时间】:2015-12-12 04:33:23
【问题描述】:
Dictionary<double, Tuple<int,int>> dictionary = new Dictionary<double, Tuple<int,int>>();

for (int i = 0; i < x.Length; i++)
    for (int j = i+1; j < x.Length; j++)
    {
        double weight = Math.Round(Math.Sqrt(Math.Pow((x[i] - x[j]), 2) + Math.Pow((y[i] - y[j]), 2)), 2);
        string edges = i + "-" + j + "-" + weight;
        listBox1.Items.Add(edges);
        Tuple<int, int> tuple = new Tuple<int, int>(i, j);
        dictionary.Add(weight, tuple);
    }

var list = dictionary.Keys.ToList();
list.Sort();

foreach (var key in list)
{
    string a = dictionary[key].Item1 + "--" + dictionary[key].Item2 + "--> " + key.ToString();
    listBox2.Items.Add(a);
}

我正在尝试将一些值存储在字典中。但是在 for 循环中突然中断了不完整的值。没有错误信息。 当我注释掉“dictionary.Add(weight, tuple);”列表框正在显示我想要的所有数据。

【问题讨论】:

  • x 到底是什么?
  • 它是所有x点的x值的x-y坐标系数组
  • 当您注释掉dictionary.Add(weight, tuple); 时,列表框怎么可能显示您想要的所有数据?列表框正在从字典中填充,如果您发表该评论,该字典将为空。
  • for 循环中的listbox1 正在填充所有数据。

标签: c# loops for-loop dictionary break


【解决方案1】:

如果您尝试将已添加的密钥 Add 转换为 Dictionary,则会抛出 DuplicateKeyException。这很可能是因为您正在四舍五入您的双精度数,从而导致几个将成为相同的值。

假设您在 UI 事件(表单、WPF 或其他)中使用 ListBox,我会说它可能 抛出异常,但还有其他东西正在捕获该异常并继续前进。

添加到字典时,应检查键是否已存在,并适当处理。

如果您想覆盖该值,请记住this[TKey key] 在添加新项目时不会抛出异常。因此

// dictionary.Add(weight, tuple);
dictionary[weight] = tuple;

如果您想跳过已经存在的值,请检查ContainsKey

if(!dictionary.ContainsKey(weight)) 
    dictionary.Add(weight, tuple);

【讨论】:

  • 我正在尝试用 z 距离将 x 保存到 y。因此,当 z 距离达到相同的值时,它总是会中断。有没有办法添加相同的键值数据
  • 不是直接的。您需要更改为不同的数据,首先要考虑的是Dictionary&lt;double, List&lt;Tuple&lt;int, int&gt;&gt;&gt; - 您可能还想考虑在这里反转键值(Tuples 作为键是有效的) - 但是,所有这些都需要大量的设计变更。
猜你喜欢
  • 1970-01-01
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多