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:

or:

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

 

Practical example

Edit

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. 

Output:

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

Edit

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

Output:

Note:

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

References

Edit
  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
1
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