Dictionary<TKey, TValue> · C#
ContainsKey / ContainsValue
ContainsKey hashes the key; ContainsValue has no index and scans every entry.
public bool ContainsKey(TKey key); public bool ContainsValue(TValue value)
Complexity
| Expected | O(1) for ContainsKey |
|---|---|
| Worst case | O(n) for ContainsValue (always) |
| Extra space | O(1) |
Keys are hashed into buckets; values are not indexed at all, so finding one means visiting every entry.
Tested example
var ages = new Dictionary<string, int> { ["ada"] = 36 };
Assert.True(ages.ContainsKey("ada"));
Assert.False(ages.ContainsValue(99)); // ContainsValue scans every entry: O(n)
Parameters
- key / value
- What to look for.
Behaviour
- Returns
- Whether it is present.
- Errors and preconditions
- ContainsKey: ArgumentNullException for a null key.
- Changes
- Nothing.
- Memory and invalidation
- No allocation.