C# Linq 中的多重 Where 子句


使用 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

更新時間:23-6-2020

4K+ 瀏覽量

開啟你的 職業生涯

透過完成課程來獲得認證

開始吧
廣告
© . All rights reserved.