Helper us
Helper us

Reputation: 33

Change dictionary key by value

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

Answers (3)

BendEg
BendEg

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

Ivan Yonkov
Ivan Yonkov

Reputation: 7034

You most probably do NOT want to do this. There are some variables here:

  1. What happens with the previous key-value pair? Does apple get changed with pear?

  2. What if pear already exists? What happens with its value?

  3. 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

IS4
IS4

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

Related Questions