How to insert an item into a C# list by using an index?


Firstly, set a list −

List<int> list = new List<int>();
list.Add(456);
list.Add(321);
list.Add(123);
list.Add(877);
list.Add(588);
list.Add(459);

Now, to add an item at index 5, let say; for that, use the Insert() method −

list.Insert(5, 999);

Let us see the complete example −

Example

using System;
using System.Collections.Generic;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         List<int> list = new List<int>();
         list.Add(456);
         list.Add(321);
         list.Add(123);
         list.Add(877);
         list.Add(588);
         list.Add(459);
         Console.Write("List: ");

         foreach (int i in list) {
            Console.Write(i + " ");
         }
         Console.WriteLine("
Count: {0}", list.Count);          // inserting element at index 5          list.Insert(5, 999);          Console.Write("
List after inserting a new element: ");          foreach (int i in list) {             Console.Write(i + " ");          }          Console.WriteLine("
Count: {0}", list.Count);       }    } }

Updated on: 22-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements