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

การตรวจสอบว่า List มีสมาชิกที่ตรงตามเงื่อนไขใน C#

ภาพรวม

เมธอด List<T>.Exists(Predicate<T>) ใช้ตรวจสอบว่ามีสมาชิกอย่างน้อยหนึ่งตัวที่ทำให้ predicate คืน true หรือไม่ คืนค่า boolean

ตัวอย่างที่ 1: ตรวจสอบว่ามีตัวเลขหาร 3 ลงตัวหรือไม่

using System;
using System.Collections.Generic;

public class Demo
{
    private static bool demo(int i)
    {
        return ((i % 3) == 0);
    }

    public static void Main(String[] args)
    {
        List<int> list = new List<int>();
        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("Does some elements match the predicate = " + list.Exists(demo));
    }
}

ผลลัพธ์

List elements...
255
315
410
500
600
710
800
1000
Does some elements match the predicate = True

ตัวอย่างที่ 2: ตรวจสอบว่ามีตัวเลขหาร 7 ลงตัวหรือไม่ (ไม่มี)

using System;
using System.Collections.Generic;

public class Demo
{
    private static bool demo(int i)
    {
        return ((i % 7) == 0);
    }

    public static void Main(String[] args)
    {
        List<int> list = new List<int>();
        list.Add(255);
        list.Add(310);
        list.Add(410);
        list.Add(500);
        list.Add(600);

        Console.WriteLine("List elements...");
        foreach (int i in list)
        {
            Console.WriteLine(i);
        }

        Console.WriteLine("Does some elements match the predicate = " + list.Exists(demo));
    }
}

ผลลัพธ์

List elements...
255
310
410
500
600
Does some elements match the predicate = False

สรุป

  • Exists หยุดทันทีเมื่อพบตัวแรกที่ตรงเงื่อนไข (short-circuit)
  • Predicate สามารถเป็น lambda expression ได้ เช่น list.Exists(x => x % 3 == 0)
  • ต่างจาก FindAll ที่คืนรายการทั้งหมดที่ตรง