How to remove an item from a C# list by using an index?

CsharpProgrammingServer Side Programming

To remove an item from a list in C# using index, use the RemoveAt() method.

Firstly, set the list −

List<string> list1 = new List<string>() {
   "Hanks",
   "Lawrence",
   "Beckham",
   "Cooper",
};

Now remove the element at 2nd position i.e. index 1

list1.RemoveAt(1);

Let us see the complete example −

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;

class Program {
   static void Main() {
      List<string> list1 = new List<string>() {
         "Hanks",
         "Lawrence",
         "Beckham",
         "Cooper",
      };

      Console.Write("Initial list...");
      foreach (string list in list1) {
         Console.WriteLine(list);
      }

      Console.Write("Removing element from the list...");
      list1.RemoveAt(1);
   
      foreach (string list in list1) {
         Console.WriteLine(list);
      }
   }
}

Output

Initial list...
Hanks
Lawrence
Beckham
Cooper
Removing element from the list...
Hanks
Beckham
Cooper
raja
Published on 20-Aug-2018 10:17:54
Advertisements