The Insert method of List class inserts an object at a given position. The first parameter of the method is the 0th based index in the List.
The InsertRange method can insert a collection at the given position.
Add an item to a List
This shows how to add an item to a List using the List.Add() method. The .Add method adds an item to the end of the List by default.
1 2 3 4 5 6 | List<Drink> drinks = new List<Drinks>(); drinks.Add(new Drink{ Name = "Beer", Id=8 }); drinks.Add(new Drink{ Name = "Champagne", Id=312 }); drinks.Add(new Drink{ Name = "Lemonade", Id=14 }); |
There’s another method you can use if you want to add items to a C# List – AddRange(). It allows you to add one List to another List.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | //The List to start with 8: Beer 312: Champagne 14: Lemonade List<Drink> extraDrinks = new List<Drink> { new Drink{ Name = "Sambucca", Id=9 }, new Drink{ Name = "Prosecco", Id=192 }, new Drink{ Name = "Vodka and orange", Id=17 } }; barOrder.AddRange(extraDrinks); //The List now 8: Beer 312: Champagne 14: Lemonade 9: Sambucca 192: Prosecco 17: Vodka and orange |
Add an item to the start of a C# List – Insert
If you want to add an item to the start of the List you would use the List.Insert() method which inserts an item to the given List at the position provided. So to insert an item to the start of the List you would specify the position as 0, which is the first position in the list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //The List to start with 312: Champagne 74: Coke 88: Sparkling Water //now insert an item into the first position drinks.Insert(0, new Drink{ Name = "Orange Juice", Id=501 }; //The List now 501: Orange Juice 312: Champagne 74: Coke 88: Sparkling Water |
But to insert an item to the 3rd row of the List you would specify the position as 2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | //The List to start with 501: Orange Juice 312: Champagne 74: Coke 88: Sparkling Water drinks.Insert(2, new Drink{ Name = "Apple Juice", Id=502 }); //The List now 501: Orange Juice 312: Champagne 502: Apple Juice 74: Coke 88: Sparkling Water |
And similarly to the AddRange() method I talked about above, there is an InsertRange() method which allows you to insert a List into another List.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | //The List to start with 501: Orange Juice 312: Champagne 502: Apple Juice 74: Coke 88: Sparkling Water List<Drink> moreDrinks = new List<Drink> { new Drink{ Name = "Martini", Id=43 }, new Drink{ Name = "Mojito", Id=44 }, new Drink{ Name = "Pale Ale", Id=18 } }; //Insert this List to the 3rd row drinks.InsertRange(2, moreDrinks); //The List now 501: Orange Juice 312: Champagne 43: Martini 44: Mojito 18 Pale Ale 502: Apple Juice 74: Coke 88: Sparkling Water |