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

Nhiều mệnh đề Where trong LINQ C#

Trong LINQ, bạn có thể sử dụng nhiều mệnh đề where trong một truy vấn (query expression). Các điều kiện này được kết hợp bằng logic AND - chỉ các phần tử thỏa mãn tất cả điều kiện mới được chọn.

Ví dụ: Nhân viên có Rank > 5 VÀ Rank < 10

var res = from e in employee
          where e.Rank > 5
          where e.Rank < 10
          select e;

Mã nguồn hoàn chỉnh

using System;
using System.Linq;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        IList employee = new List()
        {
            new Employee() { EmpID = 1, EmpName = "Tom", EmpMarks = 90, Rank = 8 },
            new Employee() { EmpID = 2, EmpName = "Anne", EmpMarks = 60, Rank = 21 },
            new Employee() { EmpID = 3, EmpName = "Jack", EmpMarks = 76, Rank = 18 },
            new Employee() { EmpID = 4, EmpName = "Amy", EmpMarks = 67, Rank = 20 }
        };
        
        var res = from e in employee
                  where e.Rank > 5
                  where e.Rank < 10
                  select e;
        
        foreach (var emp in res)
        {
            Console.WriteLine("Name: " + emp.EmpName);
            Console.WriteLine("Marks: " + emp.EmpMarks);
        }
    }
}

public class Employee
{
    public int EmpID { get; set; }
    public string EmpName { get; set; }
    public int EmpMarks { get; set; }
    public int Rank { get; set; }
}

Kết quả

Name: Tom
Marks: 90

Cú pháp Method Syntax tương đương

var res = employee.Where(e => e.Rank > 5).Where(e => e.Rank < 10);

Hoặc gộp thành một lambda:

var res = employee.Where(e => e.Rank > 5 && e.Rank < 10);

Lưu ý

  • Nhiều mệnh đề where trong query syntax = AND logic.
  • Để dùng OR, hãy gộp vào một mệnh đề: where e.Rank < 5 || e.Rank > 20.
  • Thứ tự các mệnh đề where không ảnh hưởng kết quả nhưng có thể ảnh hưởng hiệu suất (đặt điều kiện lọc bớt phần tử nhiều nhất lên trước).