zoukankan      html  css  js  c++  java
  • Linq中Take与Skip的使用

    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中两者被称为分区运算符。

  • 相关阅读:
    Android AdapterView View的复用机制 分析
    go12---interface
    go11---方法method
    go10---struct
    go09---defer
    go8---函数function
    go7---map
    go6---slice切片
    go5--数组
    go4--break,continue + 标签
  • 原文地址:https://www.cnblogs.com/Arainzhe/p/9347497.html
Copyright © 2011-2022 走看看