c# - Exception upon trimming the extension of key values of dictionary -


i have dictionary key values , trying trim extension of these values exception message item same key has been added.

not sure why case.

this code used

how can overcome problem?

dictfilesnotthere = dictfilesnotthere.todictionary             (t => t.key.remove(8, 3), t => t.value); 

the key value follow '7dim-058-ns' , trying '7dim-058' instead

suppose have following items in dictionary:

dictfilesnotthere.add("7dim-058-ns", 1); dictfilesnotthere.add("7dim-058-n2", 2); dictfilesnotthere.add("7dim-058-n3", 2); 

then after removing via t.key.remove(8, 3) get: 7dim-058 key above items. since in dictionary can't have duplicate keys, why exception.

to rid of problem, can setup counter , add key, if key found in dictionary before. like:

dictionary<string, int> dictfilesnottherecopy = new dictionary<string, int>(); int counter = 0; foreach (keyvaluepair<string,int> item in dictfilesnotthere) {     if (dictfilesnottherecopy.containskey(item.key.remove(8, 3)))         dictfilesnottherecopy.add((item.key.remove(8, 3) + (counter++)).tostring(), item.value);     else         dictfilesnottherecopy.add(item.key.remove(8, 3), item.value); } 

Comments