Click here to Skip to main content
15,896,726 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Is there any better way to Update a dictionary key,


for example:

C#
var dic = new Dictionary<int, string="">();
dic.Add(103, "Alex");



and later on I decided to make key value pair to be (120 , "Alex") , is it possible to just rename the key rather than add a new key value pair of (120 , "Alex") and then remove 103 ?

What I have tried:

C#
var dic = new Dictionary<int, string>();
dic.Add(103, "Alex");




and later on I decided to make key value pair to be (120 , "Alex") , is it possible to just rename the key rather than add a new key value pair of (120 , "Alex") and then remove 103 ?
Posted
Updated 25-Mar-21 13:03pm
v3
Comments
[no name] 25-Mar-21 15:25pm    
Create a "rename" method and pretend it's not doing an add and delete.
Jon McKee 25-Mar-21 15:30pm    
If the number is the volatile data, maybe index on "Alex" instead if possible? Other than that, Gerry's response is really all you can do. Adding/deleting pairs isn't computationally expensive so it's not really an issue in my opinion.
Maciej Los 25-Mar-21 17:29pm    
Are you sure that 120 is not already in a dictionary?
PIEBALDconsult 25-Mar-21 18:59pm    
That depends on the Dictionary, how the class is implemented.
If you are using some in-house or third-party Dictionary, maybe, but not with the built-in .net Dictionary.

1 solution

There is no provided way way to alter the value of a key as MSDN states: Dictionary<TKey,TValue> Class (System.Collections.Generic) | Microsoft Docs[^]
Quote:
As long as an object is used as a key in the Dictionary<tkey,tvalue>, it must not change in any way that affects its hash value. Every key in a Dictionary<tkey,tvalue> must be unique according to the dictionary's equality comparer. A key cannot be null, but a value can be, if its type TValue is a reference type.

Which means that for value types such as int you cannot modify the key as that would change the hashcode (and value types are derived from object).
For reference types it's less cut and dried as the GetHashCode method can be overridden so any changes need to be executed with extreme caution or "unpredictable results may occur".
You would have to delete the original and add a new one.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900