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

Mur*_*tAy 0 c# dictionary loops for-loop 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);
}
Run Code Online (Sandbox Code Playgroud)

我试图在字典中存储一些值.但是在for循环中,它突然出现了不完整的值.没有错误消息.当我评论出"dictionary.Add(weight,tuple);"时 列表框显示我想要的所有数据.

Dav*_*vid 5

如果你尝试AddDictionary这是已经添加了一个键,它会抛出一个DuplicateKeyException.这非常有可能,因为你正在舍入你的双倍,导致几个将成为相同的值.

通过使用的假设ListBox,你的UI事件中使用这个(表格,WPF,或以其他方式),我会说这可能抛出一个异常,而是别的东西没收异常并继续前进.

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

如果要覆盖值,请记住,this[TKey key]不会加入新的项目时抛出异常.从而

// dictionary.Add(weight, tuple);
dictionary[weight] = tuple;
Run Code Online (Sandbox Code Playgroud)

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

if(!dictionary.ContainsKey(weight)) 
    dictionary.Add(weight, tuple);
Run Code Online (Sandbox Code Playgroud)