Phương thức Where() là một trong những phương thức LINQ quan trọng nhất, dùng để lọc (filter) các phần tử của một tập hợp dựa trên một điều kiện (predicate).
Cú pháp
IEnumerable Where(this IEnumerable source, Func predicate);
IEnumerable Where(this IEnumerable source, Func predicate); // có index
Ví dụ: Lọc phần tử >= 70
int[] arr = { 10, 30, 20, 15, 90, 85, 40, 75 };
var result = arr.Where(n => n >= 70);
// Kết quả: 90, 85, 75
Mã nguồn hoàn chỉnh
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo
{
public static void Main()
{
int[] arr = { 10, 30, 20, 15, 90, 85, 40, 75 };
Console.WriteLine("Mảng gốc:");
foreach (int a in arr) Console.WriteLine(a);
// Lọc các phần tử >= 70
IEnumerable myQuery = arr.AsQueryable().Where((n, index) => n >= 70);
Console.WriteLine("\nPhần tử >= 70:");
foreach (int res in myQuery) Console.WriteLine(res);
}
}
Kết quả
Mảng gốc:
10
30
20
15
90
85
40
75
Phần tử >= 70:
90
85
75
Các dạng predicate phổ biến
| Loại | Ví dụ |
|---|---|
| Đơn giản | x => x > 10 |
| Với index | (x, i) => i % 2 == 0 (chỉ phần tử chẵn) |
| Điều kiện phức tạp | x => x.Age > 18 && x.IsActive |
| Gọi phương thức | x => IsValid(x) |
Lưu ý
Wherethực thi trì hoãn (deferred execution) - truy vấn chỉ chạy khi duyệt kết quả.- Có thể chuỗi nhiều
Where:.Where(c1).Where(c2)tương đươngAND. - Sử dụng
AsQueryable()cho LINQ to SQL/Entities để dịch sang SQL.