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
Updated on: 2020-06-22T15:30:13+05:30

471 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements