เมธอด Last() ใน LINQ ใช้ดึงองค์ประกอบสุดท้ายของ Sequence หาก Sequence ว่าง จะโยน InvalidOperationException
ตัวอย่างพื้นฐาน
using System;
using System.Linq;
using System.Collections.Generic;
class Demo
{
static void Main()
{
int[] val = { 10, 20, 30, 40 };
// ดึงองค์ประกอบสุดท้าย
int last = val.Last(); // หรือ val.AsQueryable().Last()
Console.WriteLine("Last element: " + last);
}
}
ผลลัพธ์
Last element: 40
เมธอดที่เกี่ยวข้อง
| เมธอด | คำอธิบาย | Empty Sequence |
|---|---|---|
Last() | องค์ประกอบสุดท้าย | Throw InvalidOperationException |
LastOrDefault() | องค์ประกอบสุดท้าย หรือ Default | Default Value (0, null, etc.) |
Last(predicate) | องค์ประกอบสุดท้ายที่ Match เงื่อนไข | Throw หากไม่มี Match |
LastOrDefault(predicate) | องค์ประกอบสุดท้ายที่ Match หรือ Default | Default Value |
ตัวอย่างเพิ่มเติม
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Last Even Number
int lastEven = numbers.Last(n => n % 2 == 0); // 10
// LastOrDefault - ปลอดภัยกับ Empty
int[] empty = { };
int result = empty.LastOrDefault(); // 0 (default(int))
int result2 = empty.LastOrDefault(-1); // -1 (Custom Default - C# 6+? Actually need DefaultIfEmpty)
// With Condition - Safe
int lastBig = numbers.LastOrDefault(n => n > 100); // 0 (No match)
int lastBig2 = numbers.Where(n => n > 100).DefaultIfEmpty(-1).Last(); // -1
ประสิทธิภาพ
- Array/List: O(1) - เข้าถึง Index สุดท้ายโดยตรง
- IEnumerable (Streaming): O(n) - ต้องวนจนจบ
- ใช้
TryGetLast(C# 10+/ .NET 6+) สำหรับ Pattern Matching
// C# 10+ / .NET 6+
if (numbers.TryGetLast(out int last))
{
Console.WriteLine(last);
}