How to Remove Element from List in C# - Simple Guide
In C#, you can remove an element from a list using
Remove(item) to delete the first matching item, RemoveAt(index) to remove by position, or RemoveAll(predicate) to remove all items matching a condition. These methods modify the list directly.Syntax
Here are the main ways to remove elements from a List<T> in C#:
Remove(item): Removes the first occurrence ofitemfrom the list.RemoveAt(index): Removes the element at the specifiedindex.RemoveAll(predicate): Removes all elements that satisfy thepredicatecondition.
csharp
list.Remove(item); list.RemoveAt(index); list.RemoveAll(x => x == value);
Example
This example shows how to remove elements from a list using different methods:
csharp
using System; using System.Collections.Generic; class Program { static void Main() { List<string> fruits = new List<string> { "apple", "banana", "cherry", "banana" }; // Remove first "banana" fruits.Remove("banana"); // Remove element at index 1 ("cherry" after removal above) fruits.RemoveAt(1); // Remove all elements equal to "banana" fruits.RemoveAll(f => f == "banana"); foreach (var fruit in fruits) { Console.WriteLine(fruit); } } }
Output
apple
Common Pitfalls
Common mistakes when removing elements from a list include:
- Trying to remove an item that does not exist, which returns
falsebut does not throw an error. - Using
RemoveAtwith an invalid index, which throws anArgumentOutOfRangeException. - Modifying a list while iterating over it, which can cause runtime errors.
Always check if the item exists or if the index is valid before removing.
csharp
/* Wrong: Removing while iterating causes error */ // foreach (var item in list) { // if (item == "banana") list.Remove(item); // } /* Right: Use RemoveAll or iterate on a copy */ list.RemoveAll(item => item == "banana");
Quick Reference
| Method | Description | Returns |
|---|---|---|
| Remove(item) | Removes first matching item | bool (true if removed) |
| RemoveAt(index) | Removes item at given index | void |
| RemoveAll(predicate) | Removes all items matching condition | int (count removed) |
Key Takeaways
Use Remove(item) to delete the first matching element from a list.
Use RemoveAt(index) to remove an element by its position safely.
Use RemoveAll(predicate) to remove all elements that meet a condition.
Avoid modifying a list while iterating over it to prevent errors.
Check for valid indexes and existence of items before removing.