C# List insert elements example

In this source code example, we will demonstrate how to insert elements in a List in C#. 

The Insert method inserts an element into the list at the specified index. 

The InsertRange inserts the elements of a collection into the list at the specified index.

C# List insert elements example

The following example creates a new list of fruits and inserts new elements into it.

using System;
using System.Collections.Generic;

public class ListDemo
{
    public static void Main(string[] args)
    {
        var fruits = new List<string> { "banana", "mango", "apple", "watermelon" };
        
        fruits.Insert(0, "orange");
        fruits.Insert(fruits.Count, "pear");
        
        var fruits2 = new List<string> { "grapes", "blackberry" };
        fruits.InsertRange(2, fruits2);
        
        fruits.ForEach(Console.WriteLine);
    }
}

Output:

orange
banana
grapes
blackberry
mango
apple
watermelon
pear

Comments