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

CsharpProgrammingServer Side Programming

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("\nCount: {0}", list.Count);

         // inserting element at index 5
         list.Insert(5, 999);
         Console.Write("\nList after inserting a new element: ");

         foreach (int i in list) {
            Console.Write(i + " ");
         }
         Console.WriteLine("\nCount: {0}", list.Count);
      }
   }
}
raja
Published on 31-Aug-2018 12:05:58
Advertisements