C# Linq 中的多个 Where 子句
csharpprogrammingserver side programming更新于 2025/8/11 8:52:17
在 C# 中使用 Where 子句过滤集合。单个查询表达式可能包含多个 where 子句。
首先,设置一个集合 −
IList<Employee> employee = new List<Employee>() {
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} ,
};
现在,让我们使用多个 where 子句来获取排名大于 5 且小于 10 的员工。
var res = from e in employee where e.Rank > 5 where e.Rank < 10 select e;
以下是代码 −
示例
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
public static void Main() {
IList<Employee> employee = new List<Employee>() {
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; }
}
输出
Name: Tom Marks: 90

