FirstOrDefault() trả về phần tử đầu tiên hoặc giá trị mặc định (0 cho numeric, null cho reference) nếu collection rỗng. Tránh ngoại lệ.
Ví dụ minh họa
using System;
using System.Collections.Generic;
using System.Linq;
class Demo
{
static void Main()
{
List<float> val = new List<float> { };
float a = val.AsQueryable().FirstOrDefault();
Console.WriteLine("Giá trị mặc định = " + a);
if (a == 0.0f)
a = 0.1f;
Console.WriteLine("Giá trị mặc định float cập nhật = " + a);
}
}
Kết quả đầu ra
Giá trị mặc định = 0 Giá trị mặc định float cập nhật = 0.1
Ứng dụng: Xử lý an toàn collection có thể rỗng. Kết hợp ?? (null-coalescing) cho reference type: list.FirstOrDefault() ?? "Default".