ใช้เมธอด List<T>.Find(Predicate<T>) ค้นหาองค์ประกอบ ตัวแรก ที่ตรงตามเงื่อนไข คืนค่า Default (null/0) หากไม่พบ
ตัวอย่าง: หาตัวเลขแรกที่หาร 2 ลงตัว
using System;
using System.Collections.Generic;
using System.Linq;
class Demo
{
static void Main()
{
List myList = new List { 5, 10, 17, 19, 23, 33 };
Console.WriteLine("List:");
foreach (int i in myList) Console.WriteLine(i);
int val = myList.Find(item => item % 2 == 0);
Console.WriteLine("Element divisible by 2: " + val);
}
}
ผลลัพธ์
List: 5 10 17 19 23 33 Element divisible by 2: 10
เมธอดที่เกี่ยวข้อง: FindAll (คืน List ทุกตัวที่ตรง), FindIndex (คืน Index), FindLast (ค้นจากท้าย), Exists (คืน bool)