1

I had a list of strings.

I wanted to delete one in it as follows:

  settings.RecentSearches.Keys.Remove(itemToAdd.Key);
  settings.RecentSearches.Keys.Add(itemToAdd.Key);

Error:

Mutating a key collection derived from a dictionary is not allowed.

I wanted to add and delete values in it.

What can i do?

Nahum
  • 6,959
  • 12
  • 48
  • 69
C Sharper
  • 8,284
  • 26
  • 88
  • 151

4 Answers4

7

You can't remove an item from the collection of keys of a dictionary. You have to remove the item from the dictionary itself using Dictionary.Remove.

ken2k
  • 48,145
  • 10
  • 116
  • 176
2

Remove

settings.RecentSearches.Remove(itemToAdd.Key);


Add settings.RecentSearches[itemToAdd.Key] = itemToAdd.Value;

This will add the key to the dictionary if the key already not exists. If the key already exists, the value will be overwritten. To avoid, overwriting, have a if check.

Albert
  • 51
  • 5
1

Well i'm not C# background guy. I suggest you one of the idea that may help you,

  1. Create dictionary class category or subclass of dictionary.
  2. Save your key value in temporary variable.
  3. Remove your key from dictionary directly.
  4. Add your new key and set your temporary variable saved value under that key.
Tirth
  • 7,801
  • 9
  • 55
  • 88
1

The problem is you are using Keys.Add and Keys.Remove, not the .Add and .Remove methods of the Dictionary itself.

settings.RecentSearches.Remove(itemToAdd.Key);
settings.RecentSearches.Add(itemToAdd.Key);
Boluc Papuccuoglu
  • 2,318
  • 1
  • 14
  • 24