Last and LastOrDefault Methods in Linq

Last and LastOrDefault Methods in Linq

In this article, I am going to discuss the Last and LastOrDefault Methods in Linq with some examples. Please read our previous article before proceeding to this article, where we discussed the First and FirstOrDefault methods in Linq with some examples.

Last Method in Linq: 

The Last Method in Linq is used to return the last element from a data source. There are two overloaded versions available for the Last method as shown below.

Last and LastOrDefault Methods in Linq

As you can see, the first overloaded version of the Last method does not take any parameter. It simply returns the last element from the data source and if the data source is empty then it throws an exception.

The second overloaded version of the Last method takes a predicate as a parameter. Using this predicate we can specify a condition and then it returns the last element which satisfied the specified condition. In this case, if no element satisfied the specified condition, then it will throw an exception.

Example1: Return the last element from a data source.

In the following example, we have created a data source which contains integer numbers from 1 to 10. So, as per our requirement, we need to fetch the last element from the data source i.e. the value 10 as it is the last element present in the data source.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int MethodSyntax = numbers.Last();
            Console.WriteLine(MethodSyntax);

            Console.ReadLine();
        }
    }
}

Now, run the application and it should print 10 in the output window as expected.

Example2: Return the last element from the data source which is less than 5.

Here we need to specify a condition, so we need to use the second overloaded version of the Last method which takes a predicate as a parameter. The following program uses the second overloaded version of the Last method to return the last element from the data source which is less than 5.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int MethodSyntax = numbers.Last(num => num < 5);
            Console.WriteLine(MethodSyntax);

            Console.ReadLine();
        }
    }
}

Output: 4

This is because 4 is the last element in the sequence which is less than 5

Example3: InvalidOperationException

If the data source is empty or if no element is satisfied the given condition, then it will throw the InvalidOperationException as shown in the below example.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Empty Data Source
            List<int> numbersEmpty = new List<int>() { };
            int MethodSyntax1 = numbersEmpty.Last();

            //Specified condition does not return any element
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int MethodSyntax2 = numbers.Last(num => num > 50);

            Console.ReadLine();
        }
    }
}

Now if you run the application, you will get the following exception.

Linq Last Method Throwing Exception

If you don’t want that Invalid Operation Exception, instead if you want a default value to be return based on the data type then you need to use the LastOrDefault method.

Note: the default is NULL for the reference types, and for the value types, the default value depends on the actual type expected.

LastOrDefault Method in Linq:

The LastOrDefault method exactly does the same thing as the Linq Last method except that the LastOrDefault method does not throw Invalid Operation Exception instead it returns the default value based on the data type of the element. Like the Last method, there are also two overloaded versions available for LastOrDefault method as shown below.

Last and LastOrDefault Methods in Linq

Example4: Fetch the last element from the data source using FirstOrDefault.
using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int MethodSyntax = numbers.LastOrDefault();
            Console.WriteLine(MethodSyntax);

            Console.ReadLine();
        }
    }
}

Output: 10

Example5: Fetch the last element from the data source which is less than 5.
using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int MethodSyntax = numbers.LastOrDefault(num => num < 5);
            Console.WriteLine(MethodSyntax);

            Console.ReadLine();
        }
    }
}

Output: 4

Example6:

In the below example, we have two data sources. The first data source does not contain any element and from this data source, we are trying the fetch the last element using the LastOrDefault method. The second data source contains 10 elements from the number 1 to 10 and from this data source we are trying retrieve the last element which is greater than 50.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Empty Data Source
            List<int> numbersEmpty = new List<int>() { };
            int MethodSyntax1 = numbersEmpty.LastOrDefault();
            Console.WriteLine(MethodSyntax1);

            //Specified condition doesnot return any element
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int MethodSyntax2 = numbers.LastOrDefault(num => num > 50);
            Console.WriteLine(MethodSyntax2);

            Console.ReadLine();
        }
    }
}

Here it will print the values as 0 and 0. This is because the data source contains integers. And the default for integer is 0.

Example7: Last and LastOrDefault method Using Query Syntax

There is no such operator called Last and LastOrDefault is available to write the query syntax, If you want then you can combine both the method syntax and query syntax to write the code as shown in the below example.

using System.Linq;
using System;
using System.Collections.Generic;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

            int QuerySyntax1 = (from num in numbers
                                select num).Last();

            int QuerySyntax2 = (from num in numbers
                                select num).LastOrDefault();

            Console.WriteLine(QuerySyntax1);
            Console.WriteLine(QuerySyntax2);
            Console.ReadLine();
        }
    }
}
What is the difference between Last and LastOrDefault methods in Linq?

Both Last and LastOrDefault methods in Linq are used to return the last element from a data source. But if the data source is empty or if no element is satisfied the specified condition, then the Last method will throw an exception while the LastOrDefault method will not throw an exception instead it returns a default value based on the data type of the element.

In the next article, I am going to discuss Single and SingleOrDefault Method with some example. In this article, I try to explain the Last and LastOrDefault method with some examples. I hope you understood the need and use of these Last and LastOrDefault methods in Linq.

Leave a Reply

Your email address will not be published. Required fields are marked *