The List<T>
class in C# represents a collection of items that can be indexed, searched, sorted, and manipulated. The class provides three methods to allow the removal of elements from the list:
List.Remove()
List.RemoveAt()
List.Clear()
List.Remove()
The Remove()
method takes an item as a parameter and removes the first occurrence of that item from the list
The code snippet below illustrates the usage of the Remove()
method:
using System.Collections.Generic;class RemoveDemo{static void Main(){// Creating a list of stringsList<string> Fruits = new List<string>();// Adding items to the listFruits.Add("Apple");Fruits.Add("Banana");Fruits.Add("Mango");System.Console.WriteLine("Original List:");// Printing the listFruits.ForEach(System.Console.WriteLine);// Calling the Remove() methodFruits.Remove("Banana");System.Console.WriteLine();System.Console.WriteLine("After removing Banana:");// Printing the listFruits.ForEach(System.Console.WriteLine);}}
List.RemoveAt()
The RemoveAt()
method takes a zero-based index number as a parameter and removes the item at that index.
The code snippet below illustrates the usage of the RemoveAt()
method:
using System.Collections.Generic;class RemoveDemo{static void Main(){// Creating a list of stringsList<string> Fruits = new List<string>();// Adding items to the listFruits.Add("Apple");Fruits.Add("Banana");Fruits.Add("Mango");System.Console.WriteLine("Original List:");// Printing the listFruits.ForEach(System.Console.WriteLine);// Calling RemoveAt() methodFruits.RemoveAt(1);System.Console.WriteLine();System.Console.WriteLine("After removing item at index 1:");// Printing the listFruits.ForEach(System.Console.WriteLine);}}
List.Clear()
The Clear()
method removes all elements from the list.
The code snippet below illustrates the method of the Clear()
method:
using System.Collections.Generic;class RemoveDemo{static void Main(){// Creating a list of stringsList<string> Fruits = new List<string>();// Adding items to the listFruits.Add("Apple");Fruits.Add("Banana");Fruits.Add("Mango");System.Console.WriteLine("Original List:");// Printing the listFruits.ForEach(System.Console.WriteLine);// Calling RemoveAt() functionFruits.Clear();System.Console.WriteLine();System.Console.WriteLine("After clearing the list:");// Printing the listFruits.ForEach(System.Console.WriteLine);}}
Free Resources