Runtime: Feature Request: Add `AddOrUpdate` to the Dictionary API

Created on 30 Dec 2019  路  8Comments  路  Source: dotnet/runtime

There is a Add(TKey key, TValue value) method but it throws if using a key that is already in use.

Adding AddOrUpdate(TKey key, TValue value) will simply use an existing key or add it.

Simply to be more clear and avoid boilerplate code and possibly an unnecessary lookup.

PR coming soon as it's fairly trivial.

api-suggestion area-System.Collections

All 8 comments

Isn't it what the indexer does?

Maybe, do you have a link reference?

Ah yes, I suppose what I'm advocating is to avoid having to use that syntax. Instead the simple update would look something like this:

public static void AddOrUpdate<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
  dictionary[key] = value;
}

//usage
var dictionary = new Dictionary<string, string>();

dictionary.Add("myKey", "someValue");//succeeds
dictionary.Add("myKey", "someValue");//duplicate key exception

dictionary.AddOrUpdate("myKey", "someValue");//succeeds
dictionary.AddOrUpdate("myKey", "someValue2");//succeeds

_Note: that I'm using it as an extension method at present._

I'll hold on the PR for now.

I second the request for AddOrUpdate. The Indexer does the same thing but you can't pass indexers as Funcs and such. I'd also request a GetOrAdd method similar to what ConcurrentDictiony has.

To match the shape of ConcurrentDictionary the return type should be TValue.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

yahorsi picture yahorsi  路  3Comments

iCodeWebApps picture iCodeWebApps  路  3Comments

matty-hall picture matty-hall  路  3Comments

GitAntoinee picture GitAntoinee  路  3Comments

sahithreddyk picture sahithreddyk  路  3Comments