Home > Mobile >  C# | Dictionary | How to increase or decrease numeric value of an existing key in one line
C# | Dictionary | How to increase or decrease numeric value of an existing key in one line

Time:04-24

In Java, it is possible to increase or decrease numeric value in one line while adding an element to a hashmap. Is there any way to do it in C# Dictionary?

For example in Java:

hashMap.put(key, hashMap.getOrDefault(key, 0)  1);

in C#:

if (dictionary.ContainsKey(key)) dictionary[key]  ;
else dictionary.Add(key, 1);

CodePudding user response:

One form:

dictionary[key] = dictionary.ContainsKey(key) ? dictionary[key]   1 : 1;

Another form:

dictionary[key] = dictionary.TryGetValue(key, out var x) ? x   1 : 1;

Yet another form:

if(!dictionary.TryAdd(key, 1)) dictionary[key]  ;

Close to your Java:

dictionary[key] = dictionary.GetValueOrDefault(key, 0)   1;

Note that availability of these methods vary across versions and flavours of .net - the examples above are in rough order of "available since the start of time" to "available more recently" -

In C# nothing stops you writing a GetValueOrDefault / TryAdd / TryGetValue extension if your version doesn't have some functionality you want. You don't have to subclass Dictionary to add it, see e.g. here for an example of writing an extension method to add GetValueOrDefault

CodePudding user response:

There is extension method GetValueOrDefault, so if you are ok with Java version you can easily port it.

Beware that this single statement will do lookup twice. In perf critical code or when working with a lot of data, you can consider to store simple wrapper/holder over int value and in one search/lookup extract or add slot and then simply increment value without re-searching again.

CodePudding user response:

public bool TryAdd(TKey key, TValue value);

and in order not to make a mistake, you can act like this.

public bool TryAdd(TKey key, TValue value)
{
    if (ContainsKey(key)) return false;
    Add(key, value);
    return true;
}

CodePudding user response:

​In .NET 6 it is possible to do it not only in one line, but also with only one hashcode lookup:

CollectionsMarshal.GetValueRefOrAddDefault(dictionary, key, out _)  ;

The System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault method:

Gets a reference to a TValue in the specified dictionary, adding a new entry with a default value if the key does not exist.

  • Related