C # directly to the collection dictionary and modify the value of the values, will error, the following code will error: The collection has been modified, may not be able to perform enumeration operations. The code is as follows
Public voidForeachdic () {Dictionary<string, int32> dic =NewDictionary<string, int32>(); Dic. ADD ("1",Ten); Dic. ADD ("2", -); Dic. ADD ("3", -); foreach(Keyvaluepair<string, Int32> kvpinchdic) {Console.WriteLine (String.Format ("key:{0}; Value:{1}", kvp. Key, kvp. Value)); DIC[KVP. Key]= -;//This action will cause an error: The collection has been modified, and the enumeration operation may not be performed. } }
The workaround is that we can create an additional array to iterate through the collection values, with the following code:
Private voidForeachdic () {Dictionary<string, int32> dic =NewDictionary<string, int32>(); Dic. ADD ("1",Ten); Dic. ADD ("2", -); Dic. ADD ("3", -); String[] Keyarr= dic. Keys.toarray<string>(); for(inti =0; i < keyarr.length; i++) {Dic[keystr[i]]= Dic[keystr[i]] +1; } }
C # DIctionary: The collection has been modified and may not be able to perform enumeration operations