How to remove elements from a list in C#

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

svg viewer

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<string> Fruits = new List<string>();
// 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);
}
}

List.RemoveAt()

The RemoveAt() method takes a zero-based index number as a ​parameter and removes the item at that index.

svg viewer

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<string> Fruits = new List<string>();
// 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);
}
}

List.Clear()

The Clear() method removes all elements from the list.

svg viewer

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<string> Fruits = new List<string>();
// 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);
}
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved