values - Cómo modificar la clave en un diccionario en C#
initialize dictionary c# (4)
¿Cómo puedo cambiar el valor de varias teclas en un diccionario?
Tengo el siguiente diccionario:
SortedDictionary<int,SortedDictionary<string,List<string>>>
Quiero recorrer este diccionario ordenado y cambiar la tecla a la tecla + 1 si el valor de la clave es mayor que cierta cantidad.
Debe eliminar los elementos y volver a agregarlos con su nueva clave. Por MSDN :
Las claves deben ser inmutables, siempre que se utilicen como claves en
SortedDictionary(TKey, TValue).
Como dijo Jason, no puede cambiar la clave de una entrada de diccionario existente. Tendrás que eliminar / agregar usando una nueva clave como esta:
// we need to cache the keys to update since we can''t
// modify the collection during enumeration
var keysToUpdate = new List<int>();
foreach (var entry in dict)
{
if (entry.Key < MinKeyValue)
{
keysToUpdate.Add(entry.Key);
}
}
foreach (int keyToUpdate in keysToUpdate)
{
SortedDictionary<string, List<string>> value = dict[keyToUpdate];
int newKey = keyToUpdate + 1;
// increment the key until arriving at one that doesn''t already exist
while (dict.ContainsKey(newKey))
{
newKey++;
}
dict.Remove(keyToUpdate);
dict.Add(newKey, value);
}
Si no te molesta volver a crear el diccionario, puedes usar una declaración LINQ.
var dictionary = new SortedDictionary<int, SortedDictionary<string, List<string>>>();
var insertAt = 10;
var newValues = dictionary.ToDictionary(
x => x.Key < insertAt ? x.Key : x.Key + 1,
x => x.Value);
return new SortedDictionary<int, SortedDictionary<string, List<string>>>(newValues);
o
var dictionary = new SortedDictionary<int, SortedDictionary<string, List<string>>>();
var insertAt = 10;
var newValues = dictionary.ToDictionary(
x => x.Key < insertAt ? x.Key : x.Key + 1,
x => x.Value);
dictionary.Clear();
foreach(var item in newValues) dictionary.Add(item.Key, item.Value);
Puedes usar la declaración LINQ para ello
var maxValue = 10
sd= sd.ToDictionary(d => d.key > maxValue ? d.key : d.Key +1, d=> d.Value);