1. 程式人生 > >Linq中Take與Skip的使用

Linq中Take與Skip的使用

.class 運算符 cti 個學生 esp top 提取 entity 實例

eg:現要求查詢出class_id為2的班級中年齡最大的3個學生的姓名

使用SQL語句查詢時,代碼如下所示。

select top 3 student_name from tb_Student where class_id=2 order by student_age

在Linq中使用Take()方法結合orderby子句一起來實現

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5  
 6 namespace TakeAndSkipExp
7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 using (TestDBEntities myDbEntity = new TestDBEntities()) 13 { 14 var query = from student in myDbEntity.tb_Student 15 where student.class_id == 2
16 select student; 17 Console.WriteLine("2班年齡最大的3個學生是:"); 18 var top3Student = query.OrderBy(it => it.student_age).Take(3); 19 foreach (var s in top3Student) 20 { 21 Console.WriteLine(s.student_name);
22 } 23 Console.WriteLine("2班其他的學生是:"); 24 var otherStudent = query.OrderBy(it => it.student_age).Skip(3); 25 foreach (var s in otherStudent) 26 { 27 Console.WriteLine(s.student_name); 28 } 29 } 30 } 31 } 32 }

由以上代碼可分析出:

Take()方法的作用就是:從查詢結果中提取前n個結果。而實例中出現的Skip()方法正好是Take()方法的反面,它可以跳過前n個結果,返回剩余的結果。

在Linq中兩者被稱為分區運算符。

Linq中Take與Skip的使用