Trusted answers to developer questions

How to remove elements from a list in C#

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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:

Press + to interact
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:

Press + to interact
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:

Press + to interact
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);
}
}

RELATED TAGS

remove
list
c#
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?