---
title: "What are LINQ Last(), and LastOrDefault() functions?"  
description: "What are LINQ Last(), and LastOrDefault() functions?"  
author: "Amrith Chandran"  
published: 2025-02-12  
updated: 2025-02-12  
canonical: https://www.mindstick.com/forum/161155/what-are-linq-last-and-lastordefault-functions  
category: "linq"  
tags: ["linq", "linq function"]  
reading_time: 2 minutes  

---

# What are LINQ Last(), and LastOrDefault() functions?

What are LINQ Last(), and LastOrDefault() [functions](https://www.mindstick.com/forum/160140/explain-the-role-of-functions-as-a-service-faas-in-serverless-computing)?

## Replies

### Reply by Ashutosh Patel

#### Last() vs LastOrDefault() in LINQ (C#)

**Last()** and **LastOrDefault()** both retrieve the last element from a collection, but they behave differently when no matching element is found.

#### Last()

- Returns the last element in the collection that matches a given condition.
- Throws an exception (InvalidOperationException) if no matching element is found.

## Example-

```cs
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
   static void Main()
   {
       List<int> numbers = new List<int> { 3, 7, 8, 10, 15 };
       int lastEven = numbers.Last(n => n % 2 == 0);
       Console.WriteLine("Last Even Number: " + lastEven);
       // Output: Last Even Number: 10
   }
}
```

#### LastOrDefault()

- Returns the last matching element, or the default value (null for reference types, 0 for numeric types) if no element is found.
- Does not throw an exception when no element matches.

## Example-

Finding Last Even Number, with Default Handling

```cs
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
   static void Main()
   {
       List<int> numbers = new List<int> { 3, 7, 8, 10, 15 };
       int lastEven = numbers.LastOrDefault(n => n % 2 == 0);
       Console.WriteLine("Last Even Number: " + lastEven);
       // Output: Last Even Number: 10 (if present) or 0 (if no match)

       // with string
       List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
       string result = names.LastOrDefault(n => n.StartsWith("Z"));
       Console.WriteLine(result == null ? "No match found" : result);
       // Output: No match found

   }
}
```

## When to use what?

- Use Last() when you are sure that at least one matching element exists.
- Use LastOrDefault() when no matching element exists (to avoid exceptions).

**Also, Read**: [Explain First(), FirstOrDefault() function in LINQ with C#](https://www.mindstick.com/forum/161154/explain-first-firstordefault-function-in-linq-with-c-sharp)


---

Original Source: https://www.mindstick.com/forum/161155/what-are-linq-last-and-lastordefault-functions

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
