更改字典键的最佳方法
我想知道是否有更好的方法来更改字典键,例如:
var dic = new Dictionary(); dic.Add("a", 1);
后来我决定将键值对设为(“b”,1),是否可以重命名键而不是添加新的键值对(“b”,1)然后删除“a” ?
提前致谢。
不,一旦添加到词典中,您就无法重命名键。 如果你想要一个重命名工具,也许可以添加你自己的扩展方法:
public static void RenameKey(this IDictionary dic, TKey fromKey, TKey toKey) { TValue value = dic[fromKey]; dic.Remove(fromKey); dic[toKey] = value; }
c#中的Dictionary
实现为哈希表。 因此,如果您能够通过某些Dictionary.ChangeKey
方法更改密钥,则必须重新散列该条目。 因此,删除条目,然后使用新密钥再次添加条目并不是真正的(除了方便)。
public static bool ChangeKey(this IDictionary 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的答案相同,但不会抛出exception,而是在失败时返回false
。 事实上,我认为这样的方法应该是字典类中的默认值,因为编辑键值是危险的,所以类本身应该给我们一个安全的选项。
你喜欢这个简单的代码吗?
var newDictionary= oldDictionary.ReplaceInKeys
它在所有键中用
'-'
替换'_'
如果
- 你的
key
类型是string
和
- 你想要在字典的所有键中用其他字符串替换字符串
然后用我的方式
您只需将以下类添加到您的应用中:
public static class DicExtensions{ public static void ReplaceInKeys(this IDictionary oldDictionary, string replaceIt, string withIt) { // Do all the works with just one line of code: return oldDictionary .Select(x=> new KeyValuePair(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; })
- 比较DataView.RowFilter中的日期?
- 使用IBindingList在WinForms中进行数据绑定在空列表中失败
- Combobox将itemsource绑定到自定义列表,将selecteditem绑定到该列表的实例不起作用
- Datagrid不会刷新已更改的数据
- 我使用通用限制来阻止特定类型
- 通过openFileDialog打开Web文件夹(Sharepoint 2007)
- 安装文件的位置 – Program Files(x86)\ Reference Assemblies \ Microsoft \ Framework \ .NETFramework \ v4.5
- 如何续订过期的ClickOnce证书?
- 如何在MVC中单击按钮时将模型从视图传递到控制器?