Insert an element at second position in a C# List


Here is our list −

List<string> val = new List<string> ();

// list of strings
val.Add("water");
val.Add("food");
val.Add("air");

Use the Insert() method to insert an element in the list. With that, also set where you want to add it. We have set the new text at position 1st −

val.Insert(1, "shelter");

The following is the complete code −

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      List<string> val = new List<string> ();
      // list of strings
      val.Add("water");
      val.Add("food");
      val.Add("air");
      Console.WriteLine("Initial list:");
      // Initial List
      foreach (string res in val) {
         Console.WriteLine(res);
      }
      // inserting an element at second position
      val.Insert(1, "shelter");
      Console.WriteLine("New list after inserting an element:");
      foreach (string res in val) {
         Console.WriteLine(res);
      }
   }
}

Output

Initial list:
water
food
air
New list after inserting an element:
water
shelter
food
air

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 22-Jun-2020

399 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements