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

การดึงสมาชิกทั้งหมดของ List ที่ตรงตาม Predicate ใน C#

ภาพรวม

เมธอด List<T>.FindAll(Predicate<T>) คืน List<T> ใหม่ที่มีสมาชิกทุกตัวที่ทำให้ predicate คืน true

ตัวอย่างที่ 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(9);
        list.Add(15);
        list.Add(20);
        list.Add(40);
        list.Add(50);
        list.Add(60);

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

        Console.WriteLine(" ");
        List<int> res = new List<int>(list.FindAll(demo));
        Console.WriteLine("List that match the conditions...");
        foreach (int i in res)
        {
            Console.WriteLine(i);
        }
    }
}

ผลลัพธ์

List elements...
9
15
20
40
50
60
List that match the conditions...
9
15
60

ตัวอย่างที่ 2: หาตัวเลขที่หาร 100 เหลือ 5

using System;
using System.Collections.Generic;

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

    public static void Main(String[] args)
    {
        List<int> list = new List<int>();
        list.Add(900);
        list.Add(1500);
        list.Add(250);
        list.Add(405);

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

        Console.WriteLine(" ");
        List<int> res = new List<int>(list.FindAll(demo));
        Console.WriteLine("List that match the conditions...");
        foreach (int i in res)
        {
            Console.WriteLine(i);
        }
    }
}

ผลลัพธ์

List elements...
900
1500
250
405
List that match the conditions...
405

สรุป

  • FindAll คืน List ใหม่ ไม่เปลี่ยน List เดิม
  • Predicate สามารถเป็น lambda ได้: list.FindAll(x => x % 3 == 0)
  • หากต้องการแค่ตัวแรก ใช้ Find หากต้องการดัชนี ใช้ FindIndex