EN
C# / .NET - remove last element from List
3
points
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.