What is the difference between Last() and LastOrDefault() in Linq C#?

CsharpServer Side ProgrammingProgramming

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

 Live Demo

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

 Live Demo

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.

raja
Published on 08-Aug-2020 15:06:57
Advertisements