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

ใช้หลายเงื่อนไข Where ใน LINQ C#

ใน LINQ Query Syntax สามารถใช้คำสั่ง where หลายครั้งในคิวรีเดียวกันได้ ซึ่งจะทำงานเหมือนเงื่อนไข AND (ทั้งสองต้องเป็นจริง)

ตัวอย่าง: หาพนักงานที่ Rank > 5 และ Rank < 10

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

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

    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);
        }
    }
}

ผลลัพธ์

Name: Tom
Marks: 90

เทียบเท่า: where e.Rank > 5 && e.Rank < 10 หรือใช้ Method Syntax: .Where(e => e.Rank > 5 && e.Rank < 10)