Languages
[Edit]
EN

C# / .NET - remove last element from List

3 points
Created by:
Theodora-Battle
528

In this article, we would like to show you how to remove last element from List in C#.

Quick solution:

List<int> myList = new List<int> { 1, 2, 3, 4 };

myList.RemoveAt(myList.Count - 1); // [ 1, 2, 3]

or:

List<int> myList = new List<int> { 1, 2, 3, 4 };

List<int> newList = myList.SkipLast(1).ToList();

Note: SkipLast() method was introduced in .NET 6.

 

Practical example

In this example, we use Count property with -1 to get the last index of the List. Then we use RemoveAt() method to remove element under the last index. 

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<int> myList = new List<int> { 1, 2, 3, 4 };

        // get last index of myList
        int lastIndex = myList.Count - 1;

        // remove last element
        myList.RemoveAt(lastIndex);

        // display result
        foreach (int item in myList)
            Console.WriteLine(item);
    }
}

Output:

1
2
3

2. Using SkipLast() from Linq (.NET 6)

In this example, we use SkipLast() method from System.Linq to create copy with removed last element from myList.

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<int> myList = new List<int> { 1, 2, 3, 4 };
        List<int> newList = myList.SkipLast(1).ToList();

        foreach (int item in newList)
            Console.WriteLine(item);
    }
}

Output:

1
2
3

Note:

The SkipLast() method was introduced in .NET 6, check your version before you use it.

References

  1. List<T>.Count Property (System.Collections.Generic) | Microsoft Docs
  2. Enumerable.SkipLast<TSource>(IEnumerable<TSource>, Int32) Method (System.Linq) | Microsoft Docs
  3. List<T>.RemoveAt(Int32) Method (System.Collections.Generic) | Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join