Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the Key of a Dictionary

Tags:

c#

dictionary

I am very new to dictionaries. Very new meaning that I started using them about 6 hours ago :p. Anyways, I want to know if there is a way to change the key of a dictionary.

Here is my dictionary:

Dictionary<string, string> Information = new Dictionary<string, string>();

Here is how I am adding to the dictionary (this is fired every time the user enters info and hits a button:

Information.Add(txtObjectNumber.Text, addressCombined);

The user needs to be able to edit both fields as well as remove the whole record.

So pretty much the application needs to add txtNumber and txtComments where txtNumber = txtObjectNumber

Thank you for your help.

like image 287
JLott Avatar asked Jun 13 '12 20:06

JLott


3 Answers

It is not possible to directly modify a key. You'd have to remove it and re-add it.

like image 122
Arran Avatar answered Sep 19 '22 02:09

Arran


The key is the mechanism that will allow you to find the data (the "value") later.

For example, if you did

information.Add("Kris", "Vandermotten");

you'd be able to find "Vandermotten" back later if you know "Kris".

Now in that context, what does it mean to change "Kris"? You put data in under the name "Kris" and want to get it back out searching for "Bob"? You won't find it.

In a way, dictionary key's are very much like primary keys in a relational database. The refer to the logical identity of the value. So for one thing, they should be uniquely identifying it.

So maybe this example doesn't make sense. Maybe something like

information.Add(42, new Person("Kris", "Vandermotten")

makes more sense. The question then of course is: what's the 42? Sometimes there is a natural candidate for such a key, like an employee number or something, sometimes there isn't.

When there is none, maybe you need to do

List<Person> information = new List<Person>();

information.Add(new Person("Kris", "Vandermotten"));

And of course, if a Person object allows changing the first name property, and that's what you want to do, then do it. But "changing dictionary keys" doesn't make a lot of sense to me.

like image 39
Kris Vandermotten Avatar answered Sep 22 '22 02:09

Kris Vandermotten


You could use the built-in Remove() method for your Dictionary. Or you could do it the hard way by iterating through the collection. Although I'm curious as to why you would need to have to constantly update the keys, and not the values only.

like image 31
ehmBEE Avatar answered Sep 19 '22 02:09

ehmBEE