List.Insert() method with example in C#

C# List.Insert() strategy: Here, we will find out about the Insert() technique for List with example.

C# List.Insert() Method

List.Insert() strategy is utilized to embed a component at the indicated list in the rundown.

Syntax:

    void List<T>.Insert(int index, T item);

Parameter: It acknowledges two parameters 1) list – where you need to embed the component and 2) thing – to embed in the rundown.

Return value: It returns nothing – it’s arrival type is void.

Example:

    int list declaration:
    List<int> a = new List<int>();

    adding elements:
    a.Add(10);
    a.Add(20);
    a.Add(30);
    a.Add(40);
    a.Add(50);
    
    //inserting elements at specified indexes
    a.Insert(1, 100);
    a.Insert(3, 200);
    a.Insert(4, 300);
    
    Output:
    10 100 20 200 300 30 40 50

C# Example to embed a component at a determined list in the rundown utilizing List.Insert() Method:

using System;
using System.Text;
using System.Collections.Generic;

namespace Test
{
    class Program
    {
        static void printList(List<int> lst)
        {
            //printing elements
            foreach (int item in lst)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            //integer list
            List<int> a = new List<int>();

            //adding elements
            a.Add(10);
            a.Add(20);
            a.Add(30);
            a.Add(40);
            a.Add(50);

            //print the list
            Console.WriteLine("list elements...");
            printList(a);

            //inserting elements at specified indexes
            a.Insert(1, 100);
            a.Insert(3, 200);
            a.Insert(4, 300);

            //list after inserting elements
            Console.WriteLine("list elements after inserting elements...");
            printList(a);

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output:

list elements...
10 20 30 40 50
list elements after inserting elements...
10 100 20 200 300 30 40 50

Leave a Comment

error: Alert: Content is protected!!