Adding Items To An Existing List In C# & .NET
[C#, .NET, Data Structures]
When working with the generic List, you will naturally have to add elements to the said List
.
There are several ways to do this:
Constructor Initialization
If you know the elements you need to add at compile time, you can add them using constructor initialization.
List<int> list = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Collection Initialization
Similarly, if you know the elements at compile time, you can add them using collection initialization, which works with most of the other collections.
List<int> list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
Add Method
You can add single elements using the Add method.
// Add single element
List<int> list = [];
list.Add(1);
list.Add(2);
AddRange Method
You can add multiple elements using the AddRange method. This will add the elements to the end of the collection.
// Add multiple elements
List<int> list = [];
list.AddRange([1, 2, 3, 4, 5, 6, 7, 8, 9]);
Insert Element In Position
If you have an element and you want to insert it into a particular position, you can use the Insert method, which specifies the position and the element to insert.
// Add elements at particular position
List<int> list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
list.Insert(0, -1);
list.ForEach(Console.Write);
Console.WriteLine();
Inserting Multiple Elements In Position
If you have a number of elements and you want to insert them into a particular position, you can use the InsertRange method which specifies the position to insert and the elements to insert.
// Add range of elements at particular position
List<int> list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
list.InsertRange(0, [-1, -2, -3, -4]);
list.ForEach(Console.Write);
Console.WriteLine();
You can also use LINQ to add elements to an existing List
and return a new List
:
TLDR
There are several ways to add elements to a List
.
The code is in my GitHub.
Happy hacking!