【问题标题】:changing values of dictionary keys [duplicate]更改字典键的值[重复]
【发布时间】:2013-12-26 13:00:31
【问题描述】:

我有一个字符串列表。

我想删除其中的一个,如下所示:

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

错误:

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

我想在其中添加和删除值。

我能做什么?

【问题讨论】:

  • RecentSearches 属性的类型是什么?
  • @SergeyLitvinov public MruDictionary 最近搜索;
  • @NahumLitvin no...not

标签: c# .net


【解决方案1】:

您不能从字典的键集合中删除项目。您必须使用 Dictionary.Remove 从字典本身中删除该项目。

【讨论】:

  • 但它不会从键中删除
  • @LOLSinger 确实如此。如果您从字典中删除一个项目,关联的键也将被删除。
  • 谢谢先生,它删除了密钥
【解决方案2】:

删除

settings.RecentSearches.Remove(itemToAdd.Key);


添加 settings.RecentSearches[itemToAdd.Key] = itemToAdd.Value;

如果键不存在,这会将键添加到字典中。如果键已经存在,则该值将被覆盖。为避免覆盖,请进行 if 检查。

【讨论】:

    【解决方案3】:

    嗯,我不是 C# 背景的人。我建议你一个可能对你有帮助的想法,

    1. 创建字典类类别或字典的子类。
    2. 将您的键值保存在临时变量中。
    3. 直接从字典中删除您的密钥。
    4. 添加新密钥并将临时变量保存的值设置为 那把钥匙。

    【讨论】:

      【解决方案4】:

      问题是您使用的是 Keys.Add 和 Keys.Remove,而不是 Dictionary 本身的 .Add 和 .Remove 方法。

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

      【讨论】:

        猜你喜欢
        • 2020-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-02
        • 2020-12-16
        • 2018-11-11
        • 2021-04-14
        • 1970-01-01
        相关资源
        最近更新 更多