-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Closed
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Collectionshelp wanted[up-for-grabs] Good issue for external contributors[up-for-grabs] Good issue for external contributors
Milestone
Description
It's very common to see code that does this:
Dictionary<TKey, TValue> data = ...;
...
if (!data.ContainsKey(key))
data.Add(key, value);This forces the dictionary to lookup the key twice when the key isn't yet in the dictionary.
It'd be great if we had an additional method on the type:
public bool TryAdd(TKey key, TValue value);Functionally it would behave exactly as if it were implemented like:
public bool TryAdd(TKey key, TValue value)
{
if (ContainsKey(key)) return false;
Add(key, value);
return true;
}but the implementation internally would be done more efficiently, essentially implemented by calling a variant of Insert but that returns false instead of throwing when a duplicate key is found.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Collectionshelp wanted[up-for-grabs] Good issue for external contributors[up-for-grabs] Good issue for external contributors