ภาพรวม
เมธอด List<T>.Find(Predicate<T>) คืนสมาชิก แรก ที่ทำให้ predicate คืน true หาไม่เจอคืน default(T) (null สำหรับ reference type, 0 สำหรับ int, ฯลฯ)
ตัวอย่าง 1: หาตัวเลขหาร 10 ลงตัว
using System;
using System.Collections.Generic;
public class Demo {
private static bool demo(int i) {
return ((i % 10) == 0);
}
public static void Main(String[] args) {
List list = new List();
list.Add(200);
list.Add(215);
list.Add(310);
list.Add(500);
list.Add(600);
Console.WriteLine("List elements...");
foreach (int i in list) {
Console.WriteLine(i);
}
Console.WriteLine("First Occurrence = " + list.Find(demo));
}
}
ผลลัพธ์ตัวอย่าง 1
List elements... 200 215 310 500 600 First Occurrence = 200
ตัวอย่าง 2: หาตัวเลขคู่
using System;
using System.Collections.Generic;
public class Demo {
private static bool demo(int i) {
return ((i % 2) == 0);
}
public static void Main(String[] args) {
List list = new List();
list.Add(255);
list.Add(315);
list.Add(410);
list.Add(500);
list.Add(600);
list.Add(710);
list.Add(800);
list.Add(1000);
Console.WriteLine("List elements...");
foreach (int i in list) {
Console.WriteLine(i);
}
Console.WriteLine("First Occurrence = " + list.Find(demo));
}
}
ผลลัพธ์ตัวอย่าง 2
List elements... 255 315 410 500 600 710 800 1000 First Occurrence = 410
สรุป
Findคืนแค่ตัวแรกที่เจอ (O(n))- ใช้ lambda ได้:
list.Find(x => x % 10 == 0) - มี
FindLast(ค้นจากท้าย),FindAll(คืน List ทั้งหมดที่เจอ),FindIndex(คืนดัชนี)