How to remove items from a list in C#?

ProgrammingServer Side ProgrammingCsharp

Firstly, set a list and add elements.

List<string> myList = new List<string>();
myList.Add("Jennings");
myList.Add("James");
myList.Add("Chris");

Let’s say you need to delete the element “James” now. For that, use the Remove() method.

myList.Remove("James");

Here is the complete code.

Example

 Live Demo

using System.Collections.Generic;
using System;
class Program {
   static void Main() {
      List<string> myList = new List<string>();
      myList.Add("Jennings");
      myList.Add("James");
      myList.Add("Chris");
      Console.WriteLine("Initial List...");

      foreach(string str in myList) {
         Console.WriteLine(str);
      }
      myList.Remove("James");
      Console.WriteLine("New List...");

      foreach(string str in myList) {
         Console.WriteLine(str);
      }
   }
}

Output

Initial List...
Jennings
James
Chris
New List...
Jennings
Chris
raja
Published on 11-Sep-2018 11:56:55
Advertisements