Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด Linq First() ใน C#


ภาพรวม

เมธอด First() ใน LINQ ใช้ดึง องค์ประกอบแรก ของลำดับ (sequence) เช่น อาร์เรย์ หรือ Collection หากลำดับว่าง จะโยน InvalidOperationException

รูปแบบการใช้งาน

int[] arr = {20, 40, 60, 80, 100};
int first = arr.AsQueryable().First(); // หรือ arr.First()

ตัวอย่างโค้ดเต็ม

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] arr = {20, 40, 60, 80, 100};
        int res = arr.AsQueryable().First();
        Console.WriteLine(res); // 20
    }
}

ผลลัพธ์

20

เมธอดที่เกี่ยวข้อง

  • FirstOrDefault() - คืนค่า default (0 สำหรับ int) หากลำดับว่าง ไม่โยน Exception
  • Last() / LastOrDefault() - ดึงองค์ประกอบสุดท้าย
  • Single() - คาดหวังว่ามีเพียงองค์ประกอบเดียว โยน Exception หากมีมากกว่า 1