【问题标题】:how to modify the value of an int Key in C# [duplicate]如何在C#中修改int Key的值[重复]
【发布时间】:2018-03-24 12:59:41
【问题描述】:

我有一个:

Dictionary<string, Dictionary<int, List<string>>> res = new Dictionary<string, 
Dictionary<int, List<string>>>();

我需要修改/更改嵌套字典键的 int 值,并为 int 键保留所有字典值( List )。

【问题讨论】:

    标签: c# dictionary


    【解决方案1】:

    如果我理解正确:

    res[stringKey].Add(newKey, res[oldKey]);
    res[stringKey].Remove(oldKey);
    

    【讨论】:

      【解决方案2】:

      据我所知,没有实现此目的的本地方法,但您可以尝试以下方法:

      private void ModifyKey(int oldKey, int newKey, Dictionay<int, List<string>> dict)
      {
          var data = dict[oldKey];
          // Now remove the previous data
          dict.Remove(key);
          try
          {
              dict.Add(newKey, data);
          }
          catch
          {
              // one already exists..., perhaps roll back or throw
          }
      }
      

      然后,当您要更改密钥时,您可以按如下方式调用该方法:

      // Assuming the dictionary is called myData
      ModifyKey(5, 7, myData);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-14
        • 2021-03-02
        • 2014-08-29
        • 2010-10-30
        • 2021-08-21
        • 1970-01-01
        相关资源
        最近更新 更多