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.
Use using System.Collections.Generic; at the top of the C# file, before its class definitions. Place the following statements inside an existing method.
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 value | Contains result | IndexOf result |
|---|---|---|
| 2 | true | 0 |
| 0 | true | 1 |
| 7 | false | -1 |
These examples use the established Player class and its public integer field NumberOfTurns.
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.