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:
xxxxxxxxxx
1
List<int> myList = new List<int> { 1, 2, 3, 4 };
2
3
myList.RemoveAt(myList.Count - 1); // [ 1, 2, 3]
or:
xxxxxxxxxx
1
List<int> myList = new List<int> { 1, 2, 3, 4 };
2
3
List<int> newList = myList.SkipLast(1).ToList();
Note:
SkipLast()
method was introduced in .NET 6.
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.
xxxxxxxxxx
1
using System;
2
using System.Linq;
3
using System.Collections.Generic;
4
5
public class Program
6
{
7
public static void Main()
8
{
9
List<int> myList = new List<int> { 1, 2, 3, 4 };
10
11
// get last index of myList
12
int lastIndex = myList.Count - 1;
13
14
// remove last element
15
myList.RemoveAt(lastIndex);
16
17
// display result
18
foreach (int item in myList)
19
Console.WriteLine(item);
20
}
21
}
Output:
xxxxxxxxxx
1
1
2
2
3
3
In this example, we use SkipLast()
method from System.Linq
to create copy with removed last element from myList
.
xxxxxxxxxx
1
using System;
2
using System.Linq;
3
using System.Collections.Generic;
4
5
public class Program
6
{
7
public static void Main()
8
{
9
List<int> myList = new List<int> { 1, 2, 3, 4 };
10
List<int> newList = myList.SkipLast(1).ToList();
11
12
foreach (int item in newList)
13
Console.WriteLine(item);
14
}
15
}
Output:
xxxxxxxxxx
1
1
2
2
3
3
Note:
The
SkipLast()
method was introduced in .NET 6, check your version before you use it.