0

I have a Dictionary<string, int> ad I'd like to amend the int.

I am unable to do so as it's read only.

My effort is

using System;
using System.Linq;
using System.Collections.Generic;
                    
public class Program
{
    public static void Main()
    {
        var itemInList = new Dictionary<string, int>();
        itemInList.Add("a", 0);                    
                       
         var existing = itemInList.SingleOrDefault(a => a.Key == "a");
         existing.Value++;         //fails
    }
}

I don't understand what I need to do to fix this

MyDaftQuestions
  • 4,487
  • 17
  • 63
  • 120
  • One idea is to not use `var` if you don't know what the type is. Look up the type and you'll see it's a [`KeyValuePair`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.keyvaluepair-2?view=netcore-3.1), which is a struct, and since structs are value types, you're only modifying a *copy* of the dictionary item. Also, note that `SingleOrDefault` may return the default for the type if the condition is never true, which would have a `null` key and `0` value. – Rufus L Aug 27 '20 at 19:55

2 Answers2

3

You can use the indexer, like this:

itemInList["a"]++;

That will use the "get" part of the indexer, increment the result, then use the "set" part of the indexer afterwards - so it's equivalent to:

itemInList["a"] = itemInList["a"] + 1;
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I'm a little confused. If I have understood right (and clearly I didn't), isn't my `var existing` a reference to the item in the `dictionary`? Thank you regardless, this is the answer – MyDaftQuestions Aug 27 '20 at 19:39
  • 1
    `existing` is a reference to a `KeyValuePair`. A KeyValuePair is immutable. When you update an entry in a dictionary, it replaces the existing KeyValuePair with a new one containing the original key and the new value. – John Wu Aug 27 '20 at 19:41
  • 1
    @MyDaftQuestions: No, `KeyValuePair<,>` is a *struct* - it's a *copy* of the entry in the dictionary, so even if you could modify it, it wouldn't change the value in the dictionary. – Jon Skeet Aug 27 '20 at 19:44
  • Jon I just came back to correct my language and you beat me to it. Of course it's a value type, so updating the Value would only update the copy of it. – John Wu Aug 27 '20 at 19:45
0

you are handling the dictionary in wrong way to set a value change your code like this:

using System;
using System.Linq;
using System.Collections.Generic;
                    
public class Program
{
    public static void Main()
    {
        var itemInList = new Dictionary<string, int>();
        itemInList.Add("a", 0);                    
                       
        itemInList["a"]+=1; //since dictionaries works on keys identifier
        //or
        ++itemInList["a"];
    }
}
Alok
  • 808
  • 13
  • 40