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 caseO(1) when it is the first element
AverageO(n)
Worst caseO(n)
Extra spaceO(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"));
Runs in the test suite on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples.Tests/Collections/ListExamples.cs

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.