2015-12-12 87 views
0
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);” listbox显示我想要的所有数据。c#字典自动打破for循环,

+0

什么是'究竟x'? –

+0

它是x-y坐标系统的数组,它的所有x个点的x值 – MuratAy

+0

当你注释掉'dictionary.Add(weight,tuple);'时,列表框怎么可能显示出你想要的所有数据?列表框从字典中填充,如果您发表该评论,该列表将为空。 – Rob

回答

5

如果您尝试将Add设置为已添加的密钥Dictionary,则会抛出DuplicateKeyException。这很有可能是因为你正在将你的双倍数加起来,导致几个数值会变成相同的值。

通过使用ListBox的,你在UI事件中使用这个(表格,WPF,或以其他方式)假设我会说这可能是抛出一个异常,而是别的东西正在迎头赶上该异常动人上。

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

如果要覆盖该值,请记住this[TKey key]而不是添加新项目时会引发异常。因此

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

如果你想跳过这是已经存在的值,检查ContainsKey

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

我想用z距离将x保存到y。所以当z距离会达到相同的值时,它会一直破裂。是否有任何解决方案添加相同的键值数据 – MuratAy

+0

不是直接。你需要改变一个不同的数据,首先要考虑的是一个'Dictionary >>' - 你也可能想在这里想到反转键值('Tuples'作为键是有效的) - 但是,这一切都需要进行大量的设计更改。 – David