Modifying items within a hashtable

B

bandroo

Hi Guys

How can I modify the items within a hashtable "in situ" so to speak?

At the moment, I am locating the item that I want, extracting it,
modifying the item, deleting the hashtable item, and then adding back
the modified item to hashtable.

This seems rather long winded, and surely there must be a simpler way
than that.
 
M

Marc Gravell

It depends on class (reference type) vs struct (value type).

For a class, you can simply obtain the reference and then make whatever
changes you need. Since there is only one object, it is immediately
reflected on the (same) object referenced from the hashtable.

For structs, this is trickier... you are given a memberwise clone, so
yes, so you would need to change the properties etc and then add it
back it - otherwise you changes disappear. Which is partly why many
structs are immutable.

Note that to do this step without having to Remove and Add (to avoid
the duplicate exception), you can use the indexer:

myDictionary[key] = value;

But note again that this isn't necessary for classes unless you wish to
change the object being referenced.

Marc
 
J

Jon Skeet [C# MVP]

bandroo said:
How can I modify the items within a hashtable "in situ" so to speak?

At the moment, I am locating the item that I want, extracting it,
modifying the item, deleting the hashtable item, and then adding back
the modified item to hashtable.

This seems rather long winded, and surely there must be a simpler way
than that.

It depends:

1) Are you trying to modify the key or the value? Changing a key is
very dangerous, as a change which impacts the hashcode could render the
entry impossible to find.

2) If you're trying to modify the value, what type is the value? If
it's a reference type which lets you make the modification directly,
then you should be fine.

If it's a reference type which doesn't allow the appropriate
modification, or a value type (mutable or not, unless it's mutable via
an interface) you'll just have to change the value associated with the
key to the new one. You don't need to delete the previous value though.
Just do:

table[key] = modifiedValue;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top