Reputation: 33
How to change key by value in Dictionary
?
I have code like this:
public Dictionary<string, int> Groups = new Dictionary<string, int>();
Groups.Add("apple", 0);
And I need do like this:
Groups.Update("0") = "pear"
Upvotes: 2
Views: 2453
Reputation: 21088
At first you have to be sure, that the key is unique in a dictionary, based on the GetHashCode
and equals method.
Second: I would delete the values by it's key and create some new one. Just store them in some other variable.
EDIT
If you want to store a list of words for a line number, use: Dictionary<int, IList<string>>
instead. Just a a tip. So you can access al words in a line over the key.
Upvotes: 1
Reputation: 7034
You most probably do NOT want to do this. There are some variables here:
What happens with the previous key-value pair? Does apple
get changed with pear
?
What if pear
already exists? What happens with its value?
What happens if you have multiple keys with the same value e.g. apple => 0
, orange => 0
. Update("0") = "pear"
would try to set both keys to pear
which is not possible and one of them will disappear
If you are still sure you want to do this, then just traverse the KeyValuePair
and find the items whose Value
is 0
. Then remove its Key
and add new key => value pair with the new key and the old value.
var key = "";
foreach (var item in dictionary)
{
if (item.Value == "desired_value")
{
key = item.Key
break;
}
}
dictionary.Remove(key);
dictionary.Add(newKey, "desired_value");
Upvotes: 3
Reputation: 13187
I don't think there is a simple method that does this, but you can find the key using LINQ, and then remove the pair:
var key = Groups.Single(p => p.Value == 0).Key;
Groups.Remove(key);
Groups.Add("pear", 0);
This also throws an exception for invalid key or multiple pairs.
Upvotes: 1