Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Kiểm tra List có chứa phần tử thỏa mãn điều kiện trong C#

Ví dụ 1

Sử dụng phương thức Exists với predicate để kiểm tra:

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("Các phần tử List...");
        foreach (int i in list) {
            Console.WriteLine(i);
        }
        
        Console.WriteLine("Có phần tử nào thỏa điều kiện? = " + list.Exists(demo));
    }
}

Kết quả

Các phần tử List...
255
315
410
500
600
710
800
1000
Có phần tử nào thỏa điều kiện? = True

Ví dụ 2

Kiểm tra điều kiện chia hết cho 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("Các phần tử List...");
        foreach (int i in list) {
            Console.WriteLine(i);
        }
        
        Console.WriteLine("Có phần tử nào thỏa điều kiện? = " + list.Exists(demo));
    }
}

Kết quả

Các phần tử List...
255
310
410
500
600
Có phần tử nào thỏa điều kiện? = False