Working with List<T>
Add, insert, read, find, remove, sort and loop through the items of a C# List<T>.
Apprentice · C# · Updated
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
Addputs 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 anArgumentOutOfRangeException. Containssays whether an item is in the list andIndexOfgives its position, or-1; both match capital letters exactly.Remove(item)takes out the first match,RemoveAt(index)the item at a position, andClearempties the list.- Don't
AddorRemoveinside aforeachover the same list. Loop through it andAddthe 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() |
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.