- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the difference between Last() and LastOrDefault() in Linq C#?
Both Last() and LastOrDefault() will fetch the last occurrence of a value. But the major difference between Last() and LastOrDefault() is that Last() will throw an exception if there is no result data for the supplied criteria whereas LastOrDefault() will return the default value (null) if there is no result data.
Use Last() when we knew the sequence will have at least one element. Use LastOrDefault() when we are not sure about the data.
Example
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace ConsoleApp { public class Student { public int Id { get; set; } public string Name { get; set; } } class Program { static void Main() { var studentsList = new List<Student> { new Student { Id = 1, Name = "John" }, new Student { Id = 2, Name = "Jack" }, new Student { Id = 1, Name = "Jill" } }; var lastOrDefaultStudent = studentsList.LastOrDefault(student => student.Id == 1); var lastStudent = studentsList.Last(student => student.Id == 1); Console.WriteLine($"LastOrDefault: {lastOrDefaultStudent.Id} {lastOrDefaultStudent.Name}"); Console.WriteLine($"Last: {lastStudent.Id} {lastStudent.Name}"); Console.ReadLine(); } } }
Output
The output of the above code is
LastOrDefault: 1 Jill Last: 1 Jill
Example
using System; using System.Collections.Generic; using System.Linq; namespace DemoApplication { class Program { static void Main(string[] args) { try { var studentsList = new List<Student> { new Student { Id = 1, Name = "John" }, new Student { Id = 2, Name = "Jack" } }; var lastOrDefaultStudent = studentsList.LastOrDefault(student => student.Id == 3); var value = lastOrDefaultStudent == null ? "null" : ""; Console.WriteLine($"LastOrDefault: {value}"); var lastStudent = studentsList.Last(student => student.Id == 3); } catch (Exception ex) { Console.WriteLine($"Last Exception: {ex.Message}"); Console.ReadLine(); } } } public class Student { public int Id { get; set; } public string Name { get; set; } } }
Output
The output of the above code is
LastOrDefault: null Last Exception: Sequence contains no matching element
Here Id "3" is not present in the studentsList. Hence LastOrDefault() is returning null value whereas Last() is throwing an exception.
Advertisements