Working with List<T>

Add, insert, read, find, remove, sort and loop through the items of a C# List<T>.

Apprentice · C# · Updated

By

After this lesson you can

  • Add, insert, read, find and remove items in a List<T>
  • Loop through a List<T> and use its Count

Key takeaways

  • Add puts an item at the end of a list; Insert(index, item) puts it at a position and shifts the rest to the right.
  • A list's indexes start at 0 and the last one is Count - 1. Reading one that isn't there stops the program with an ArgumentOutOfRangeException.
  • Contains says whether an item is in the list and IndexOf gives its position, or -1; both match capital letters exactly.
  • Remove(item) takes out the first match, RemoveAt(index) the item at a position, and Clear empties the list.
  • Don't Add or Remove inside a foreach over the same list. Loop through it and Add the items you want to keep to a new list instead.

A List<T> comes with methods for every everyday job. These are the ones you'll use most.

Add and Insert

Add puts an item at the end. Insert puts it at an index, and shifts everything after it to the right.

List<string> lineup = new List<string>();
lineup.Add("Ana");
lineup.Add("Raj");
lineup.Add("Kim");
lineup.Insert(1, "Lee");

Console.WriteLine(string.Join(", ", lineup));
Ana, Lee, Raj, Kim

Reading and changing by index

A list uses square brackets, just like an array. Indexes start at 0, and the last one is Count - 1:

List<string> lineup = ["Ana", "Lee", "Raj", "Kim"];

Console.WriteLine(lineup[0]);
Console.WriteLine(lineup[lineup.Count - 1]);

lineup[2] = "Rajesh";
Console.WriteLine(lineup[2]);
Ana
Kim
Rajesh

Reading an index that isn't there stops the program with an ArgumentOutOfRangeException, the list's version of the array's out-of-range error.

Finding items

List<string> lineup = ["Ana", "Lee", "Raj", "Kim"];

Console.WriteLine(lineup.Contains("Raj"));
Console.WriteLine(lineup.IndexOf("Raj"));
Console.WriteLine(lineup.IndexOf("Zoe"));
True
2
-1

Contains answers yes or no; IndexOf gives the position, or -1 if the item isn't there. Both compare exactly, so capital letters matter.

Removing items

Remove takes out the first item equal to the one you give it, and returns true if it found one. RemoveAt takes out the item at an index. Clear empties the list.

List<string> lineup = ["Ana", "Lee", "Raj", "Kim"];

lineup.Remove("Lee");
Console.WriteLine(string.Join(", ", lineup));

lineup.RemoveAt(0);
Console.WriteLine(string.Join(", ", lineup));

Console.WriteLine(lineup.Remove("Zoe"));

lineup.Clear();
Console.WriteLine(lineup.Count);
Ana, Raj, Kim
Raj, Kim
False
0

Looping through a list

foreach visits every item, and a for loop uses Count:

List<decimal> prices = [4.99m, 12.50m, 3.25m];

decimal total = 0;
foreach (decimal price in prices)
{
    total += price;
}
Console.WriteLine(quot;Total: {total:C}");

for (int i = 0; i < prices.Count; i++)
{
    Console.WriteLine(quot;{i + 1}. {prices[i]:C}");
}
Total: $20.74
1. $4.99
2. $12.50
3. $3.25

You can't Add or Remove items inside a foreach over the same list: C# stops the program with an InvalidOperationException, because the list changed under the loop. Build a new list instead, as in the next section.

Building a new list from an old one

A common pattern: loop through one list, and Add the items you want to keep to a new one.

List<int> scores = [21, 7, 35, 14, 3];
List<int> bigScores = new List<int>();

foreach (int score in scores)
{
    if (score >= 14)
    {
        bigScores.Add(score);
    }
}

Console.WriteLine(string.Join(", ", bigScores));
21, 35, 14

Sorting and converting

List<string> teams = ["Ohio State", "Georgia", "Alabama"];
teams.Sort();
Console.WriteLine(string.Join(", ", teams));

string[] asArray = teams.ToArray();
List<string> backToList = new List<string>(asArray);
Console.WriteLine(quot;{asArray.Length} {backToList.Count}");
Alabama, Georgia, Ohio State
3 3

Sort puts the list in order. ToArray copies a list into an array, and new List<string>(array) copies an array into a list.

Quick reference

To Write
add to the end list.Add(item)
add at a position list.Insert(index, item)
read or change list[index]
count list.Count
check for an item list.Contains(item)
find its position list.IndexOf(item)
remove an item list.Remove(item)
remove at a position list.RemoveAt(index)
empty it list.Clear()
sort it list.Sort()

Do it: save a spot in line for a friend

At the concert, people wait in a lineup. A person in line may save one spot for a friend: the friend goes right behind them, and everyone after moves back one place.

The method gets three values:

  • lineup: a List<string> of the names in line, the front of the line first.
  • name: the person saving the spot.
  • friend: the friend who joins the line.

For example, Lee saves a spot for Zoe:

List<string> lineup = new List<string> { "Ana", "Lee", "Raj", "Kim" };
string name = "Lee";
string friend = "Zoe";
Step Result
Find Lee's place in the lineup 1
The spot right behind Lee 2
Put Zoe at place 2; Raj and Kim move back Ana, Lee, Zoe, Raj, Kim

So SaveSpot(lineup, "Lee", "Zoe") returns the list { "Ana", "Lee", "Zoe", "Raj", "Kim" }.

Your job: write the method SaveSpot(List<string> lineup, string name, string friend) so it returns the lineup, a List<string>, with the friend in it.

  • Put friend right behind name.
  • When name is last in line, the friend goes at the end.
  • When name isn't in the lineup at all, the friend goes at the end. An empty lineup has no names, so the friend is the only one in it.
  • Return the lineup.

Practiced live on the lesson page: write the C# right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

With Add, Remove, an index and a loop, a list handles almost any group of data that changes, and you never shift an element by hand again.

Key terms

Cheat sheets