2.4.14 Removing an Item From a List

Removing an Item From a List

The coach removes a recorded score or a player entry. Choose whether the argument describes a value, an object reference, or an index.

Explore the idea
Remove by value

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

Remove the first matching integer
List<int> roundGoals = new List<int>();
roundGoals.Add(2);
roundGoals.Add(0);
roundGoals.Add(2);
roundGoals.Add(3);
bool removed = roundGoals.Remove(2);

Remove searches for the supplied item and removes only its first match. removed becomes true; the remaining values are 0, 2, 3. A missing value produces false and leaves the list unchanged.

Remove by index
Continue after removing the first 2
roundGoals.RemoveAt(1);

Before this call the list is 0, 2, 3. Index 1 holds 2, so the list becomes 0, 3 and Count becomes 2. Later entries shift left. RemoveAt returns no result value and throws ArgumentOutOfRangeException for an invalid index. Check that the index is at least 0 and less than Count before using an uncertain position.

Remove by object reference

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

Remove one roster entry
Player jordan = new Player();
jordan.NumberOfTurns = 2;
Player casey = new Player();
casey.NumberOfTurns = 1;
List<Player> players = new List<Player>();
players.Add(jordan);
players.Add(casey);
players.Add(jordan);

bool removedJordan = players.Remove(jordan);

For this Player class with no custom equality behavior, Remove matches the same object reference. The remaining entries are Casey at index 0 and Jordan at index 1. removedJordan is true. Only one Jordan entry was removed, and the Jordan variable still reaches the same Player.

Matching fields do not make the same Player
Player anotherPlayer = new Player();
anotherPlayer.NumberOfTurns = 2;
bool removedAnother = players.Remove(anotherPlayer);

removedAnother is false. The new Player has the same turn count as Jordan but a different identity. To remove whichever object occupies a known position, use RemoveAt with that position instead.

Trace the worked example
Independent integer list snapshots show 2, 0, 2, 3 before Remove(2), then 0, 2, 3, then 0, 3 after RemoveAt(1).
Compare successive states after value and index removal
  • New
  • Changed
  • Removed
Predict and check