Ví dụ 1
Sử dụng FindAll với predicate để lọc phần tử:
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("Các phần tử List...");
foreach (int i in list) {
Console.WriteLine(i);
}
Console.WriteLine(" ");
List<int> res = new List<int>(list.FindAll(demo));
Console.WriteLine("Các phần tử thỏa điều kiện...");
foreach (int i in res) {
Console.WriteLine(i);
}
}
}
Kết quả
Các phần tử List...
9
15
20
40
50
60
Các phần tử thỏa điều kiện...
9
15
60
Ví dụ 2
Lọc số chia hết cho 100 dư 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("Các phần tử List...");
foreach (int i in list) {
Console.WriteLine(i);
}
Console.WriteLine(" ");
List<int> res = new List<int>(list.FindAll(demo));
Console.WriteLine("Các phần tử thỏa điều kiện...");
foreach (int i in res) {
Console.WriteLine(i);
}
}
}
Kết quả
Các phần tử List...
900
1500
250
405
Các phần tử thỏa điều kiện...
405