Подтвердить что ты не робот

Как изменить ключ в словаре в С#

Как изменить значение количества ключей в словаре.

У меня есть следующий словарь:

SortedDictionary<int,SortedDictionary<string,List<string>>>

Я хочу пропустить этот отсортированный словарь и сменить ключ на клавишу + 1, если значение ключа больше определенной суммы.

4b9b3361

Ответ 1

Как сказал Джейсон, вы не можете изменить ключ существующей записи словаря. Вам нужно будет удалить/добавить с помощью нового ключа, например:

// 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);
}

Ответ 2

Вам нужно удалить элементы и снова добавить их своим новым ключом. Per MSDN:

Ключи должны быть неизменными, если они используются как клавиши в SortedDictionary(TKey, TValue).

Ответ 3

Если вы не возражаете воссоздать словарь, вы можете использовать статут 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); 

или

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);

Ответ 4

Вы можете использовать для него показатель LINQ

var maxValue = 10
sd= sd.ToDictionary(d => d.key > maxValue ? d.key : d.Key +1, d=> d.Value);