Dictionary<TKey, TValue> · C#
Remove
Removes a key if present; never throws for a missing key.
public bool Remove(TKey key); public bool Remove(TKey key, out TValue value)
Complexity
| Expected | O(1) |
|---|---|
| Worst case | O(n) |
| Extra space | O(1) |
Assumes: Good hash distribution.
Find the entry in its bucket chain and unlink it. Capacity is kept.
Tested example
var ages = new Dictionary<string, int> { ["ada"] = 36, ["bob"] = 25 };
Assert.True(ages.Remove("bob"));
Assert.False(ages.Remove("bob")); // already gone: false, no exception
Assert.True(ages.Remove("ada", out int removed));
Assert.Equal(36, removed);
Assert.Empty(ages);
Parameters
- key
- The key to remove.
Behaviour
- Returns
- Whether a pair was removed (and its value, in the second overload).
- Errors and preconditions
- ArgumentNullException for a null key.
- Changes
- Unlinks the entry and puts its slot on a free list for reuse.
- Memory and invalidation
- Does not shrink. Allowed during enumeration since .NET Core 3.0.