1

I am trying to make a change to a KeyValuePair and have got as far as this code from another post I found:

var keysToModify = this.Properties
                    .Where(k => k.Key == propertyName)
                    .ToList();

                foreach (var key in keysToModify)
                {
                    this.Properties[key] = newValue;
                }

But my key field is a string not an int. What would I need to do to update a KeyValuePair in this case?

EDIT : My KeyValuePair is of type string,string, and when I run the code in my example above, I get the error :

keyvaluepair is not assignable to parameter type int

Community
  • 1
  • 1
user517406
  • 13,623
  • 29
  • 80
  • 120

2 Answers2

0

The key wasn't an integer in your linked question either, it was a Customer. You should be able to use the same general method no matter what the key type is. Here's example code like the accepted answer to the other question that will work when the key is a string:

// The ToList() call here is important, so that we evaluate all of the query
// *before* we start modifying the dictionary
var keysToModify = CustomerOrderDictionary.Keys
                                          .Where(k => k == "MyString")
                                          .ToList();
foreach (var key in keysToModify)
{
    CustomerOrderDictionary[key] = 4;
}

Note that where the other answer accessed the Id property of the Customer key, you can directly compare the key to your target string.

Also, note that if you are just updating a single entry in the dictionary you don't need a loop, you can just do it directly. If you know the dictionary dictionary has an entry with the given key, or don't mind creating a new entry, just use:

CustomerOrderDictionary["MyString"] = 4;

or, to guard against creating new entry:

if (CustomerOrderDicionary.ContainsKey("MyString"))
{
    CustomerOrderDictionary["MyString"] = 4;
}
Ergwun
  • 12,579
  • 7
  • 56
  • 83
0

There is no particular magic to updating the value of the pair when the key is a string - it's much the same, you're just using a string to access a value (and this stands for any type being used as key, omitting any possible peculiarities).

But the only thing I can think might be throwing you off in this case is the loop. The loop is iterating instances, though, and isn't exposing an additive "index" in doing so, but rather key in this case would be a string.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129