【问题标题】:Best way to change dictionary key更改字典键的最佳方法
【发布时间】:2011-09-23 20:50:11
【问题描述】:

我想知道是否有更好的方法来更改字典键,例如:

var dic = new Dictionary<string, int>();
dic.Add("a", 1);

后来我决定将键值对设为 ("b" , 1) ,是否可以只重命名键而不是添加一个新的键值对 ("b",1) 然后删除“一个”?

提前致谢。

【问题讨论】:

    标签: c# dictionary


    【解决方案1】:

    不,一旦添加到字典中,您就不能重命名键。如果你想要一个重命名工具,也许添加你自己的扩展方法:

    public static void RenameKey<TKey, TValue>(this IDictionary<TKey, TValue> dic,
                                          TKey fromKey, TKey toKey)
    {
      TValue value = dic[fromKey];
      dic.Remove(fromKey);
      dic[toKey] = value;
    }
    

    【讨论】:

    • 更好的命名是ChangeKey 或UpdateKey :)
    【解决方案2】:

    c# 中的Dictionary 实现为哈希表。因此,如果您能够通过某种Dictionary.ChangeKey 方法更改密钥,则必须重新散列该条目。因此,它与删除条目然后使用新密钥再次添加它并没有什么不同(除了方便之外)。

    【讨论】:

      【解决方案3】:
      public static bool ChangeKey<TKey, TValue>(this IDictionary<TKey, TValue> dict, 
                                                 TKey oldKey, TKey newKey)
      {
          TValue value;
          if (!dict.TryGetValue(oldKey, out value))
              return false;
      
          dict.Remove(oldKey);
          dict[newKey] = value;  // or dict.Add(newKey, value) depending on ur comfort
          return true;
      }
      

      与 Colin 的回答相同,但不抛出异常,而是在失败时返回 false。事实上,考虑到编辑键值是危险的,我认为这种方法应该是字典类中的默认方法,因此类本身应该给我们一个安全的选项。


      从 .NET Core 开始,这样效率更高:

      public static bool ChangeKey<TKey, TValue>(this IDictionary<TKey, TValue> dict, 
                                                 TKey oldKey, TKey newKey)
      {
          TValue value;
          if (!dict.Remove(oldKey, out value))
              return false;
      
          dict[newKey] = value;  // or dict.Add(newKey, value) depending on ur comfort
          return true;
      }
      

      【讨论】:

      • 我喜欢这种方法,它是安全的,如果需要的话,允许失败,但我会稍微改变它,因为我正在寻找解决的边缘情况需要采取键名作为字符串。
      【解决方案4】:

      你喜欢这个简单的代码吗?

      var newDictionary= oldDictionary.ReplaceInKeys<object>("_","-");
      

      它将所有键中的'_' 替换为'-'


      如果

      • key 的类型是string

      和

      • 你想替换一个字符串与其他字符串在字典的所有键

      那么用我的方式


      您只需将以下类添加到您的应用中:

      public static class DicExtensions{
      
          public static void ReplaceInKeys<TValue>(this IDictionary<string, TValue> oldDictionary, string replaceIt, string withIt)
          {
                // Do all the works with just one line of code:
                return oldDictionary
                       .Select(x=> new KeyValuePair<string, TValue>(x.Key.Replace(replaceIt, withIt), x.Value))
                       .ToDictionary(x=> x.Key,x=> x.Value);
          }
      }
      

      我使用 Linq 来更改我的字典键(通过linq 重新生成字典)

      神奇的步骤是ToDictionary()方法。


      注意:我们可以让一个高级的Select包含一个用于复杂情况的代码块,而不是一个简单的 lambda。

      Select(item =>{
                  .....Write your Logic Codes Here....
      
                  return resultKeyValuePair;
             })
      

      【讨论】:

      • 这种方法的内存分配似乎有点快和松散,不会投反对票,但我会纯粹因为内存分配的气味而避免它,对我来说只是有点危险的一面喜欢。
      猜你喜欢
      • 2011-06-25
      • 2023-01-09
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      • 2011-08-04
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      相关资源
      最近更新 更多