❔ Entry API for dictionaries?
Rust has this nifty API called
Entry
which allows one to write code such as:
So, you can modify a value in a hashmap (dictionary) if the key exists, or insert a new entry if the key does not exist.
Is there something similar in C#?19 Replies
I don't think so.
What would the equivalent idiomatic C# code look like?
If I understand the code correctly, something like this?
Actually since the value isn't used, something like this:
I very often end up with extension methods like
IncrementOrInsert
for numeric dictionariesI think there's only a native AddOrUpdate for ConcurrentDictionaries
But not for regular Dictionaries IIRC
The closest thing I have in mind would be a TryAdd to have contains & add in one statement, but it does not allow modification of an existing entry
Just out of curiosity I tried both:
As usual, the penalty for using the thread-safe version is pretty high.
I wonder why there is no out of the box AddOrUpdate for the regular Dictionary, it's a welcome QoL addition and I think everyone would be aware that it is not an atomic threadsafe operation
GitHub
API Proposal: Add AddOrUpdate to Dictionary · Issue #26848 · dotnet...
Add the AddOrUpdate method that is on ConcurrentDictionary to Dictionary. This would improve performance in use cases such as counting keys. K-Nucleotide in the benchmarksgame does this and has an ...
This issue talks about DictionarySlim.
I've never heard of that.
Me neither
Doesn't seem like anything that ever actually shipped
Can't find anything about that on source dot net as well
GitHub
corefxlab/src/Microsoft.Experimental.Collections/Microsoft/Collecti...
This repo is for experimentation and exploring new ideas that may or may not make it into the main corefx repo. - dotnet/corefxlab
Since it's archived, feels like it didn't pan out.
CollectionsMarshal.GetValueRefOrAddDefault Method (System.Runtime.I...
Gets a reference to a TValue in the specified dictionary, adding a new entry with a default value if the key does not exist.
which you can use to efficiently implement an
AddOrUpdate
method yourself
it is "unsafe" so you do need to be mindful when using itthere are some related issues https://github.com/dotnet/runtime/issues/15059 and there seems to be little appetite to introduce convenience methods for these cases
GitHub
Propose Adding a GetOrAdd(TKey key, Func valueFactory) to Dictionar...
On ConcurrentDictionary<TKey, TValue> there is the very useful function TValue GetOrAdd(TKey key, Func<TKey, TValie> valueFactory). The pattern that the method represents is one that is...
Ohh right I remember that CollectionsMarshal did receive that, indeed
Thanks for reminding me too, I completely forgot
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.