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:

Download  Run Code

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:

Download  Run Code

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.

Download  Run Code

That’s all about adding an item at the beginning of a List in C#.