Find last element in a List in C#
This post will discuss how to find the last element in a List in C#.
1. Using Enumerable.Last Method
To retrieve the last element of a collection, use the Enumerable.Last() method. This is available in the System.Linq namespace. It can be used as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; var lastItem = nums.Last(); Console.WriteLine(lastItem); // 5 } } |
The Last() extension method throws System.InvalidOperationException if the collection contains no elements. Consider using the Enumerable.LastOrDefault() method instead, which returns the last element of a collection, or a default value if the collection is empty.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Linq; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; var lastItem = nums.LastOrDefault(); Console.WriteLine(lastItem); // 5 } } |
2. Using ^ operator
If you’re using C# 8, you can use the ^ operator to access the last element in a list. The following example shows the invocation of this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; if (nums.Count > 0) { var lastItem = nums[^1]; Console.WriteLine(lastItem); // 5 } } } |
Alternatively, you can access the last item of a list using the indexing operator. The following code example shows its usage:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; public class Example { public static void Main() { List<int> nums = new List<int>() { 1, 2, 3, 4, 5 }; if (nums.Count > 0) { var lastItem = nums[nums.Count - 1]; Console.WriteLine(lastItem); // 5 } } } |
That’s all about finding the last element in a List in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)