TheDeveloperBlog.com


C# LastOrDefault and Last Methods

LastOrDefault, last. LastOrDefault is a helpful method. It finds the last element in a collection that matches a condition. We get either the last matching element or the default value. Last meanwhile will throw an exception if no element exists.


LastOrDefault. This program shows the LastOrDefault method, which is found in the System.Linq namespace. The result is 3 for the first array. For the second array, which is empty, the result is 0 because the default int value is 0.

And: The third call yields the value 3 because 3 is the final odd value in the source array.

Odd, Even
Based on:

.NET 4.5

C# program that uses LastOrDefault method

using System;
using System.Linq;

class Program
{
    static void Main()
    {
	// Last or default.
	int[] array1 = { 1, 2, 3 };
	Console.WriteLine(array1.LastOrDefault());

	// Last when there are no elements.
	int[] array2 = { };
	Console.WriteLine(array2.LastOrDefault());

	// Last odd number.
	Console.WriteLine(array1.LastOrDefault(element => element % 2 != 0));
    }
}

Output

3
0
3

Predicate argument. The argument to the third LastOrDefault call is a predicate delegate instance. It is specified as a lambda expression. The right side returns true or false depending on the result of the expression.

LambdasPredicate

Tip: The LastOrDefault method will never throw an exception on a non-null collection reference. It will return the default value.

Null

Last. 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.

IEnumerable

Lambda: We demonstrate the Last extension method with a Predicate represented as a lambda expression.

Note: The lambda specifies that only odd numbers are accepted. The modulo expression must not return 0.

Modulo
C# program that uses Last extension

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

Internals. How does the Last extension work? It determines if the collection type implements IList. The IList interface is implemented by arrays, Lists, and others. In this case, it uses the last index and returns the last element.

IList

But: For other IEnumerable instances, the Last implementation loops through the whole collection.


Summary. Last and LastOrDefault are helpful in many programs. Last has some optimizations for Lists and arrays, but is also effective for other types of collections. LastOrDefault, unlike Last, throws no exceptions.