c#字典自动打破for循环,

时间:2015-12-12 04:33:23

标签: c# loops for-loop dictionary break

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循环中,它突然出现了不完整的值。没有错误消息。 当我注释掉&#34; dictionary.Add(weight,tuple);&#34;列表框显示我想要的所有数据。

1 个答案:

答案 0 :(得分:5)

如果您尝试AddDictionary已添加的密钥,它会抛出DuplicateKeyException。这非常有可能,因为你要对你的双倍进行舍入,导致几个变为相同的值。

假设您使用ListBox在UI事件(表单,WPF或其他方式)中使用它,我会说 可能抛出异常,但是其他东西正在抓住那个例外并继续前进。

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

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

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

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

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