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.
It is not possible to directly modify a key. You'd have to remove it and re-add it.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With