Codiqo

Learn C# · lesson 27 of 61 · about 8 minutes

List<T>

Open the chest: keep the hero's bag in a List<T> that grows with Add and shrinks with RemoveAt.

What you'll learn

  • Create a List<T>
  • Add, insert and remove items
  • Use Count and indexes

The chest at the exit

The hero carries a torch, a rope and some bread, and by the exit stands a chest. The hero picks things up one line at a time until typing done, so nobody knows in advance how many there'll be. An array can't grow, but a List<string> can: each thing goes on the end with Add. The bag only holds 5 things, so while it has more, the last thing packed is left behind with RemoveAt.

Lists grow

List<string> names = new() { "Ada", "Bo" }; makes a list of strings. The <string> says what it holds.

| Use | Does |
|---|---|
| Add(x) | add to the end |
| Insert(i, x) | add at position i |
| Remove(x) | remove the first x |
| RemoveAt(i) | remove at position i |
| Count | how many (arrays use Length) |
| list[i] | read or change an item |

A changing list

List<string> queue = new() { "Ada", "Bo" };
queue.Add("Cy");
queue.Insert(0, "Dee");
queue.Remove("Bo");
Console.WriteLine($"{string.Join(", ", queue)} ({queue.Count})");
queue[0] = "Di";
queue.RemoveAt(queue.Count - 1);
Console.WriteLine(string.Join(", ", queue));

Output

Dee, Ada, Cy (3)
Di, Ada

Tip

new List<string> { ... } and new() { ... } make the same list: with new(), C# takes the type from the left-hand side. C# 12 can also write a list's items in square brackets: List<string> bag = ["torch", "rope"];

Tip

string.Join(", ", bag) puts every item into one string with a comma and a space between them. It works for arrays and lists alike.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.