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:

Download  Run Code

 
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.

Download  Run Code

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:

Download  Run Code

 
Alternatively, you can access the last item of a list using the indexing operator. The following code example shows its usage:

Download  Run Code

That’s all about finding the last element in a List in C#.