C# List removing elements example

In this source code example, we will demonstrate how to remove elements from the List in C#.

The Remove, RemoveAt, RemoveAll, RemoveRange, and Clear methods can be used to remove elements from a list.

C# List removing elements example

The following example removes one or more elements from the list of integers.
using System;
using System.Collections.Generic;

public class ListDemo
{
    public static void Main(string[] args)
    {
        var nums = new List<int> { 0, 1, 2, -3, 4, -5, 6, 7, -8, 9, 10 };
        
        nums.RemoveAll(e => e < 0);
        Console.WriteLine(string.Join(", ", nums));
        
        nums.Remove(0);
        nums.RemoveAt(nums.Count - 1);
        
        Console.WriteLine(string.Join(", ", nums));
        
        nums.RemoveRange(0, 3);
        
        Console.WriteLine(string.Join(", ", nums));
        
        nums.Clear();
        Console.WriteLine("{0}", nums.Count);
    }
}

Output:

0, 1, 2, 4, 6, 7, 9, 10
1, 2, 4, 6, 7, 9
6, 7, 9
0
With RemoveAll method, we remove all elements that satisfy the given predicate; in our case, we remove all negative values:

        var nums = new List<int> { 0, 1, 2, -3, 4, -5, 6, 7, -8, 9, 10 };
        
        nums.RemoveAll(e => e < 0);
The Remove method removes the first occurrence of the 0 value:

        nums.Remove(0);
With RemoveAt, we remove the element at the given index:

        nums.RemoveAt(nums.Count - 1);
With the Clear method, we can clear the list:

        nums.Clear();

Related C# List Examples


Comments