Last()和LastOrDefault()都将获取值的最后一次出现。但是Last()和LastOrDefault()之间的主要区别在于,如果没有提供的条件的结果数据,Last()将引发异常,而如果没有结果数据,LastOrDefault()将返回默认值(空)。
当我们知道序列将至少包含一个元素时,请使用Last()。当我们不确定数据时,请使用LastOrDefault()。
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(); } } }
输出结果
上面代码的输出是
LastOrDefault: 1 Jill Last: 1 Jill
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; } } }
输出结果
上面代码的输出是
LastOrDefault: null Last Exception: Sequence contains no matching element
在此处,学生列表中不存在ID“ 3”。因此,LastOrDefault()返回空值,而Last()引发异常。