How to remove items from a list in C#?



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
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know


Advertisements