How to remove element from the specified index of the List in C#?

CsharpServer Side ProgrammingProgramming

To remove the element from the specified index of the List, the code is as follows −

Example

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(String[] args){
      List<string> list = new List<string>();
      list.Add("Ryan");
      list.Add("Kevin");
      list.Add("Andre");
      list.Add("Tom");
      list.Add("Fred");
      list.Add("Jason");
      list.Add("Jacob");
      list.Add("David");
      Console.WriteLine("Count of elements in the List = "+list.Count);
      Console.WriteLine("Enumerator iterates through the list elements...");
      List<string>.Enumerator demoEnum = list.GetEnumerator();
      while (demoEnum.MoveNext()) {
         string res = demoEnum.Current;
         Console.WriteLine(res);
      }
      list.RemoveAt(5);
      Console.WriteLine("\nCount of elements in the List [UPDATED] = "+list.Count);
      Console.WriteLine("Enumerator iterates through the list elements...[UPDATED]");
      demoEnum = list.GetEnumerator();
      while (demoEnum.MoveNext()) {
         string res = demoEnum.Current;
         Console.WriteLine(res);
      }
   }
}

Output

This will produce the following output −

Count of elements in the List = 8
Enumerator iterates through the list elements...
Ryan
Kevin
Andre
Tom
Fred
Jason
Jacob
David

Count of elements in the List [UPDATED] = 7
Enumerator iterates through the list elements...[UPDATED]
Ryan
Kevin
Andre
Tom
Fred
Jacob
David

Example

Let us now see another example −

 Live Demo

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(String[] args){
      List<int> list = new List<int>();
      list.Add(25);
      list.Add(50);
      list.Add(75);
      list.Add(100);
      list.Add(200);
      Console.WriteLine("Count of elements in the List = "+list.Count);
      list.RemoveAt(2);
      Console.WriteLine("\nCount of elements in the List [UPDATED] = "+list.Count);
   }
}

Output

This will produce the following output −

Count of elements in the List = 5
Count of elements in the List [UPDATED] = 4
raja
Published on 11-Dec-2019 05:31:46
Advertisements