
The last element is sometimes the most important one. With the Last extension method, you can get it with a single method call in your C# program. This simplifies some program logic.

This program instantiates an array of integers on the managed heap. Next, it calls the Last extension method on that array. Last is found in System.Linq and can be used on arrays, Lists, or anything that implements IEnumerable. We also demonstrate the Last extension method with a Predicate represented as a lambda expression; the lambda specifies that only odd numbers are accepted.
IEnumerable Predicate Type Lambda ExpressionThis C# program demonstrates the Last extension method. It requires System.Linq.
Program that uses Last extension [C#]
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] values = { 1, 2, 3, 4, 5, 6 };
int last = values.Last();
int lastOdd = values.Last(element => element % 2 != 0);
Console.WriteLine(last);
Console.WriteLine(lastOdd);
}
}
Output
6
5
How does the Last extension work? In its implementation, the method determines if the collection type implements IList. IList is implemented by arrays, Lists, and others. In this case, it simply uses the last index and returns the last element quickly. For other IEnumerable instances, it loops through the whole collection.
IList Generic Interface
We looked at the Last extension method and examined its implementation. Last has some optimizations for Lists and arrays, but is also effective for other types of collections.
LastOrDefault Method LINQ Examples