There are four ways to add items to a list:
- List.Add(): Appends an item to the end of the list.
- List.Insert(0): Adds an item to the start of the list (the 0th index).
- List initializer syntax: Add item(s) while creating the list.
- List.AddRange(): Appends multiple items to the end of the list.
I’ll show examples of all of these methods for adding to a list.
Append items with List.Add()
You can use List.Add() to append an item to the end of the list. Here’s an example:
var list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
Console.WriteLine(string.Join(",", list));
Code language: C# (cs)
This outputs the list’s contents:
1,2,3
Code language: plaintext (plaintext)
Initialize a list with items
You can create the list and add items to it at the same time by using the list initializer syntax, like this:
//Style 1
var list1 = new List<string>()
{
"Bob", "Linda", "Tina", "Gene", "Louise"
};
Console.WriteLine(string.Join(",", list1));
//Style 2 - .NET 8+
List<string> list2 = ["Bob", "Linda", "Tina", "Gene", "Louise"];
Console.WriteLine(string.Join(",", list2));
Code language: C# (cs)
This is nice syntax sugar. It’s the same as creating the list and using List.Add() to append items. This code outputs the list’s contents:
Bob,Linda,Tina,Gene,Louise
Code language: plaintext (plaintext)
Add to the start of the list with List.Insert(0)
You can use List.Insert(index) to insert an item at the specified index. The most common use of this is adding items to the beginning of the list with List.Insert(0). Here’s an example:
var list = new List<string>()
{
"B", "C"
};
list.Insert(0, "A");
Console.WriteLine(string.Join(",", list));
Code language: C# (cs)
This moves all items to the right by 1 and then adds the new item to the 0th index. This code outputs the list’s contents:
A,B,C
Code language: plaintext (plaintext)
List<T> uses a dynamically-sized array internally. This is why List.Insert() has to move items to the right before inserting the new item. It uses Array.Copy() to move items and resizes when necessary. If you’re running into performance problems with List.Insert(), and always need to insert to the head of the list, then consider using a LinkedList instead since it’s a better fit for that scenario. In my tests, I found LinkedList.AddFirst() up to 30x faster than using Insert(0) with a regular list.
Add multiple items with List.AddRange()
You can use List.AddRange() to append multiple items from an IEnumerable (list, array, etc…) to the end of the list. Here’s an example of adding all items from one list to another list:
var list = new List<int>() { 1, 2, 3 };
list.AddRange(new List<int>{ 4, 5, 6 });
Console.WriteLine(string.Join(",", list));
Code language: C# (cs)
This outputs the list’s contents:
1,2,3,4,5,6
Code language: plaintext (plaintext)