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

ตรวจสอบว่าค่าใน List ทุกค่ามากกว่าค่าที่กำหนดใน C#

ภาพรวม

ใช้ LINQ All หรือ Where ตรวจสอบว่า element ทุกตัวใน Array/List ตรงตามเงื่อนไขหรือไม่

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


using System;
using System.Linq;

namespace Demo {
    public class Program {
        public static void Main(string[] args) {
            int[] arr = { 55, 100, 87, 45 };
            int threshold = 80;

            Console.WriteLine($"Array: [{string.Join(", ", arr)}]");
            Console.WriteLine($"Threshold: {threshold}");

            // ตรวจสอบว่าทุกค่า > 80
            bool allGreater = arr.All(x => x > threshold);
            Console.WriteLine($"All greater than {threshold}: {allGreater}"); // False

            // หาค่าที่ > 80
            var greaterThan = arr.Where(x => x > threshold).ToArray();
            Console.WriteLine($"Values > {threshold}: [{string.Join(", ", greaterThan)}]"); // 100, 87

            // หาค่าที่ <= 80
            var lessOrEqual = arr.Where(x => x <= threshold).ToArray();
            Console.WriteLine($"Values <= {threshold}: [{string.Join(", ", lessOrEqual)}]"); // 55, 45
        }
    }
}

ผลลัพธ์


Array: [55, 100, 87, 45]
Threshold: 80
All greater than 80: False
Values > 80: [100, 87]
Values <= 80: [55, 45]

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

Methodคำอธิบายตัวอย่าง
All(predicate)True ถ้าทุก element matcharr.All(x => x > 80)
Any(predicate)True ถ้ามี element อย่างน้อย 1 ตัว matcharr.Any(x => x > 80)
Where(predicate)Filter elements ที่ matcharr.Where(x => x > 80)
Count(predicate)นับจำนวนที่ matcharr.Count(x => x > 80)

Manual Loop (ไม่ใช้ LINQ)


bool allGreater = true;
foreach (int val in arr) {
    if (val <= threshold) {
        allGreater = false;
        break; // Early exit
    }
}

ขยาย: Predicate Function


public static bool AllMatch<T>(this IEnumerable<T> source, Func<T, bool> predicate) {
    foreach (T item in source) {
        if (!predicate(item)) return false;
    }
    return true;
}

// ใช้งาน
bool result = arr.AllMatch(x => x > 80);