List<T> · C#
Contains / IndexOf
Searches for an element from the front, comparing with the default equality comparer.
public bool Contains(T item); public int IndexOf(T item)
Complexity
| Best case | O(1) when it is the first element |
|---|---|
| Average | O(n) |
| Worst case | O(n) |
| Extra space | O(1) |
A linear scan: nothing about a list tells where a value might be. Keep a HashSet<T> alongside, or keep the list sorted and use BinarySearch, if you search often.
Tested example
var list = new List<string> { "red", "green", "blue" };
bool found = list.Contains("green"); // linear scan with EqualityComparer<T>.Default
Assert.True(found);
Assert.Equal(2, list.IndexOf("blue"));
Assert.Equal(-1, list.IndexOf("purple"));
Parameters
- item
- The value to look for.
Behaviour
- Returns
- Contains: whether it was found. IndexOf: the first index, or -1.
- Errors and preconditions
- None.
- Changes
- Nothing.
- Memory and invalidation
- No allocation.
See it step by step: the Binary search: halving a sorted range lesson has an interactive 3D visualizer of the same mechanism.