c# 字典自动中断 for 循环,
c# dictionary automatically break the for loop,
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);" 列表框显示了我想要的所有数据。
如果您尝试 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);
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);" 列表框显示了我想要的所有数据。
如果您尝试 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);