How to remove elements from a list in C#
The List 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
Code
The code snippet below illustrates the usage of the Remove[] method:
using System.Collections.Generic;
class RemoveDemo
{
static void Main[]
{
// Creating a list of strings
List Fruits = new List[];
// Adding items to the list
Fruits.Add["Apple"];
Fruits.Add["Banana"];
Fruits.Add["Mango"];
System.Console.WriteLine["Original List:"];
// Printing the list
Fruits.ForEach[System.Console.WriteLine];
// Calling the Remove[] method
Fruits.Remove["Banana"];
System.Console.WriteLine[];
System.Console.WriteLine["After removing Banana:"];
// Printing the list
Fruits.ForEach[System.Console.WriteLine];
}
}
Run
List.RemoveAt[]
The RemoveAt[] method takes a zero-based index number as a parameter and removes the item at that index.
Code
The code snippet below illustrates the usage of the RemoveAt[] method:
using System.Collections.Generic;
class RemoveDemo
{
static void Main[]
{
// Creating a list of strings
List Fruits = new List[];
// Adding items to the list
Fruits.Add["Apple"];
Fruits.Add["Banana"];
Fruits.Add["Mango"];
System.Console.WriteLine["Original List:"];
// Printing the list
Fruits.ForEach[System.Console.WriteLine];
// Calling RemoveAt[] method
Fruits.RemoveAt[1];
System.Console.WriteLine[];
System.Console.WriteLine["After removing item at index 1:"];
// Printing the list
Fruits.ForEach[System.Console.WriteLine];
}
}
Run
List.Clear[]
The Clear[] method removes all elements from the list.
Code
The code snippet below illustrates the method of the Clear[] method:
using System.Collections.Generic;
class RemoveDemo
{
static void Main[]
{
// Creating a list of strings
List Fruits = new List[];
// Adding items to the list
Fruits.Add["Apple"];
Fruits.Add["Banana"];
Fruits.Add["Mango"];
System.Console.WriteLine["Original List:"];
// Printing the list
Fruits.ForEach[System.Console.WriteLine];
// Calling RemoveAt[] function
Fruits.Clear[];
System.Console.WriteLine[];
System.Console.WriteLine["After clearing the list:"];
// Printing the list
Fruits.ForEach[System.Console.WriteLine];
}
}
Run