2.4.11 Searching a List

Searching a List

The coach wants to know whether a score was recorded and where it first appears. Searching by value asks a different question from reading a known position.

Explore the idea
Check whether a value exists

Use using System.Collections.Generic; at the top of the C# file, before its class definitions. Place the following statements inside an existing method.

Search a sequence with a duplicate
List<int> roundGoals = new List<int>();
roundGoals.Add(2);
roundGoals.Add(0);
roundGoals.Add(2);
bool hasTwo = roundGoals.Contains(2);
int firstTwoIndex = roundGoals.IndexOf(2);

Contains returns true or false. IndexOf returns the index of the first matching item, or -1 when none matches. Here hasTwo is true and firstTwoIndex is 0, even though another 2 occupies index 2.

Search results
Search value Contains result IndexOf result
2 true 0
0 true 1
7 false -1
Search for an existing Player

These examples use the established Player class and its public integer field NumberOfTurns.

Find an object reference
Player jordan = new Player();
jordan.NumberOfTurns = 2;
List<Player> players = new List<Player>();
players.Add(jordan);

bool hasJordan = players.Contains(jordan);
int jordanIndex = players.IndexOf(jordan);

For the established Player class, which has no custom equality behavior, these searches match the same object reference. hasJordan is true and jordanIndex is 0. Matching a field value such as NumberOfTurns requires checking that field in a loop; it is not what Contains(jordan) asks.

Predict and check