Add item at the beginning of a List in C#
This post will discuss how to add an item at the beginning of a List in C#.
1. Using List<T>.Insert() method
The standard solution to inserts an element into the list at the specified index is using the List<T>.Insert() method. It can be used to add an item at the beginning of the list by passing index 0 to it, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> values = new List<int>() { 2, 3, 4, 5 }; int item = 1; values.Insert(0, item); Console.WriteLine(String.Join(", ", values)); // 1, 2, 3, 4, 5 } } |
2. Using Enumerable.Prepend() method
Starting with .NET 4.7.1, you can use the Enumerable.Prepend() method for this. It adds the specified value to the beginning of a sequence and creates a copy of it with the new element. The following code example demonstrates its usage:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> values = new List<int>() { 2, 3, 4, 5 }; int item = 1; values = values.Prepend(item).ToList(); Console.WriteLine(String.Join(", ", values)); // 1, 2, 3, 4, 5 } } |
3. Using LinkedList<T>.AddFirst() method
A better option is to use a LinkedList instead for frequent append and prepend operations. This is because a linked list uses a “double-ended queue”, which supports insertion and removal at both ends in constant time. An ArrayList, on the other hand, shifts of all latter elements to make space for the new one. The following code example adds the specified value at the beginning of a LinkedList using the AddFirst() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; public class Example { public static void Main() { LinkedList<int> values = new LinkedList<int>(); values.AddFirst(3); values.AddFirst(2); values.AddFirst(1); Console.WriteLine(String.Join(", ", values)); // 1, 2, 3 } } |
That’s all about adding an item at the beginning of a List in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)