HashSet<T> · C#
Contains
Tests membership with the set's comparer.
public bool Contains(T item)
Complexity
| Expected | O(1) |
|---|---|
| Worst case | O(n) |
| Extra space | O(1) |
Assumes: Good hash distribution.
One hash and a short chain walk, compared with a List<T>.Contains scan of the whole list.
Tested example
var words = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Apple" };
bool hasApple = words.Contains("apple"); // the comparer decides what "equal" means
bool hasPear = words.Contains("pear");
Assert.True(hasApple);
Assert.False(hasPear);
Parameters
- item
- The element to test.
Behaviour
- Returns
- Whether it is present.
- Errors and preconditions
- None.
- Changes
- Nothing.
- Memory and invalidation
- No allocation.