我想知道是否有更好的方法来更改字典键,例如:
var dic = new Dictionary<string, int>();
dic.Add("a", 1);
后来我决定将键值对设为("b",1),是否可以重命名键而不是添加新的键值对("b",1)然后删除"a" ?
提前致谢.
Col*_*inE 59
不,一旦添加到词典中,您就无法重命名键.如果你想要一个重命名工具,也许可以添加你自己的扩展方法:
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;
}
Ken*_*nde 19
在DictionaryC#中被实现为哈希表.因此,如果您能够通过某种Dictionary.ChangeKey方法更改密钥,则必须重新输入该条目.因此,删除条目,然后使用新密钥再次添加条目并不是真正的(除了方便).
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);  // do not change order
    dict[newKey] = value;  // or dict.Add(newKey, value) depending on ur comfort
    return true;
}
与Colin的答案相同,但不会抛出异常,而是false在失败时返回.事实上,我认为这样的方法应该是字典类中的默认值,因为编辑键值是危险的,所以类本身应该给我们一个安全的选项.
你喜欢这个简单的代码吗?
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;
       })