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

ความแตกต่างระหว่าง All และ Any ใน C# LINQ

ทั้ง Any() และ All() เป็น Extension Methods ใน LINQ ใช้ตรวจสอบเงื่อนไข (Predicate) กับ Sequence แต่ให้ผลลัพธ์ต่างกัน:

Method คืนค่า true เมื่อ คืนค่า false เมื่อ Short-circuit?
Any(predicate) มี อย่างน้อย 1 Element ตรงเงื่อนไข ไม่มี Element ใดตรงเงื่อนไข (หรือ Sequence ว่าง) Yes (หยุดทันทีเจอตัวแรก)
All(predicate) ทุก Element ตรงเงื่อนไข (หรือ Sequence ว่าง) มี อย่างน้อย 1 Element ไม่ตรงเงื่อนไข Yes (หยุดทันทีเจอตัวที่ไม่ผ่าน)

ตัวอย่าง Any()

var numbers1 = new List<double> { 1.2, 1.7, 2.5, 2.4 };
bool result1 = numbers1.Any(val => val < 1); // False - ไม่มีค่าน้อยกว่า 1

var numbers2 = new List<double> { 0.8, 1.7, 2.5, 2.4 };
bool result2 = numbers2.Any(val => val < 1); // True - มี 0.8 น้อยกว่า 1

Console.WriteLine(result1); // False
Console.WriteLine(result2); // True

ตัวอย่าง All()

var numbers3 = new List<double> { 0.8, 0.9, 0.6, 0.7 };
bool result3 = numbers3.All(val => val < 1); // True - ทุกค่าน้อยกว่า 1

var numbers4 = new List<double> { 0.8, 0.9, 1.0, 0.7 };
bool result4 = numbers4.All(val => val < 1); // False - มี 1.0 ไม่น้อยกว่า 1

Console.WriteLine(result3); // True
Console.WriteLine(result4); // False

กรณี Sequence ว่าง (Empty Sequence)

var empty = new List<int>();
Console.WriteLine(empty.Any(x => x > 0));  // False
Console.WriteLine(empty.All(x => x > 0));  // True (Vacuous Truth)

หมายเหตุ: All() บน Empty Sequence คืน true ตามตรรกะคณิตศาสตร์ (Vacuous Truth) เพราะไม่มี Counter-example

การใช้งานจริง

  • Any(): เช็คว่ามีข้อมูลผิดปกติหรือไม่, เช็ค Permission, เช็ค Duplicate
  • All(): Validate ว่าข้อมูลทุกอย่างผ่านเกณฑ์, เช็ค Business Rules ทุก Record

Performance

ทั้งคู่ใช้ Short-circuit Evaluation หยุดการวนลูปทันทีที่ทราบผลลัพธ์ แบบ Lazy Evaluation