相关疑难解决方法(0)

在foreach循环中编辑字典值

我正在尝试从字典中构建饼图.在我显示饼图之前,我想整理数据.我正在删除任何小于饼的5%的饼图,并将它们放入"其他"饼图中.但是我Collection was modified; enumeration operation may not execute在运行时遇到异常.

我理解为什么你不能在迭代它们时添加或删除字典中的项目.但是我不明白为什么你不能简单地改变foreach循环中现有键的值.

任何建议:修复我的代码,将不胜感激.

Dictionary<string, int> colStates = new Dictionary<string,int>();
// ...
// Some code to populate colStates dictionary
// ...

int OtherCount = 0;

foreach(string key in colStates.Keys)
{

    double  Percent = colStates[key] / TotalCount;

    if (Percent < 0.05)
    {
        OtherCount += colStates[key];
        colStates[key] = 0;
    }
}

colStates.Add("Other", OtherCount);
Run Code Online (Sandbox Code Playgroud)

.net c# .net-2.0

180
推荐指数
5
解决办法
12万
查看次数

为什么我们不能在枚举其键时更改字典的值?

class Program
    {
        static void Main(string[] args)
        {
            var dictionary = new Dictionary<string, int>()
            {
                {"1", 1}, {"2", 2}, {"3", 3}
            };

            foreach (var s in dictionary.Keys)
            {
                // Throws the "Collection was modified exception..." on the next iteration
                // What's up with that?

                dictionary[s] = 1;  

            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我完全理解为什么在枚举列表时抛出此异常 - 在枚举期间,枚举对象的结构不会改变似乎是合理的.但是,更改字典的值会改变其结构吗?具体来说,其键的结构?

c# dictionary enumeration invalidoperationexception

26
推荐指数
5
解决办法
9572
查看次数

如何在循环期间更改字典的值

如何修改Dictionary中的值?我想在我的字典中循环一个值,同时在我的字典上循环,如下所示:

for (int i = 0; i < dtParams.Count; i++)
{
   dtParams.Values.ElementAt(i).Replace("'", "''");
}
Run Code Online (Sandbox Code Playgroud)

dtParams我的位置在哪里Dictionary

我想做一些像这样的事情:

string a = "car";    
a = a.Replace("r","t");
Run Code Online (Sandbox Code Playgroud)

.net c# asp.net collections

3
推荐指数
1
解决办法
9133
查看次数

在字典中循环

我用这个:

foreach(KeyValuePair<String,String> entry in MyDic)
  {
      // do something with entry.Value or entry.Key

  }
Run Code Online (Sandbox Code Playgroud)

问题是我无法更改entry.Value或entry.Key的值

我的问题是,如何在循环字典时更改值或键?并且,字典是否允许重复密钥?如果是的话,我们怎么能避免?谢谢

c# dictionary

3
推荐指数
2
解决办法
5401
查看次数

F#System.InvalidOperationException:集合被修改; 枚举操作可能无法执行

我在F#中遇到这个问题[不是C#,其中已有类似的帖子有类似的答案]

我理解它不可能修改一个字典,而在for循环中枚举它我该如何解决?

let edgelist1 = [(1,2,3.0f);(1,2,4.0f);(5,6,7.0f);(5,6,8.0f)]
let dict_edges = new Dictionary<int*int,(int*int*float32) list>()
for x in edgelist1 do dict_edges.Add ((fun (a,b,c)-> (a,b)) x, x)
for k in dict_edges.Keys do dict_edges.[k] <- (dict_edges.[k] |> List.rev)
Run Code Online (Sandbox Code Playgroud)

System.InvalidOperationException:集合已被修改; 枚举操作可能无法执行.

System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource资源)位于System.Collections.Generic.Dictionary`2.KeyCollection.Enumerator.MoveNext()at.$ FSI_0101.main @()

这是有效的

dict_edges.[(1,2)] <- dict_edges.[(1,2)] |> List.rev;;
Run Code Online (Sandbox Code Playgroud)

在for循环中,我只需要更改字典值,而不是键.

谢谢

f# dictionary list

1
推荐指数
1
解决办法
128
查看次数