Linq C# 中 Last() 和 LastOrDefault() 有什麼區別?


Last() 和 LastOrDefault() 都會獲取某個值最後一次出現的位置。但 Last() 和 LastOrDefault() 之間的主要區別在於,如果為提供的條件找不到結果資料,則 Last() 會丟擲異常,而 LastOrDefault() 會返回預設值 (null)。

當我們知道序列中至少有一個元素時,使用 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" 不存在於 studentsList 中。因此 LastOrDefault() 返回 null 值,而 Last() 丟擲異常。

更新於: 08-Aug-2020

737 次瀏覽

開啟你的 職業

完成課程並獲得認證

開始吧
廣告
© . All rights reserved.