LINQ 语句中Take() 和Skip() 总结:
一、Take() 和Skip()
在对数据进行分区选择时常用 Take() 和Skip()
通过如下例子进行方法的效果展示:
Take() 方法:
var query = (from student in current.listInfo
where student.name.Contains("lilu")
orderby student.age descending
select student).Take(3).ToArray();
Take(3) 代表选取3个 ,如果满足条件的不足3个 那就有几个选几个 可以一个都没有,超过的话只选顺序前 3 个
Skip() 方法:
var querySkip = (from student in current.listInfo
where student.name.Contains("lilu")
orderby student.age descending
select student).Skip(3).ToArray();
Skip(3) 代表跳过3个 ,如果满足条件的不足3个 那就有几个选几个 跳过几个,超过的话只跳过顺序的前 3 个
二 完整代码示例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleAppTake
{
class Program
{
public static readonly Program current = new Program();
List<InfoMsg> listInfo = new List<InfoMsg>();
static void Main(string[] args)
{
InfoMsg infoMsg1 = new InfoMsg(15, "lilu");
InfoMsg infoMsg2 = new InfoMsg(16, "lilu2");
InfoMsg infoMsg3 = new InfoMsg(23, "lilu3");
InfoMsg infoMsg4 = new InfoMsg(24, "lilu5");
InfoMsg infoMsg5 = new InfoMsg(16, "lilu7");
InfoMsg infoMsg6 = new InfoMsg(10, "lilu9");
current.listInfo.Add(infoMsg1);
current.listInfo.Add(infoMsg2);
current.listInfo.Add(infoMsg3);
current.listInfo.Add(infoMsg4);
current.listInfo.Add(infoMsg5);
current.listInfo.Add(infoMsg6);
var query = (from student in current.listInfo
where student.name.Contains("lilu")
orderby student.age descending
select student).Take(3).ToArray();
Console.WriteLine("年龄最大的3个运动员是:");
foreach (var s in query)
{
Console.WriteLine(s.name +" "+s.age);
}
Console.WriteLine("剔除年龄最大的3个运动员后剩余的是:");
var querySkip = (from student in current.listInfo
where student.name.Contains("lilu")
orderby student.age descending
select student).Skip(3).ToArray();
foreach (var s in querySkip)
{
Console.WriteLine(s.name + " " + s.age);
}
}
class InfoMsg
{
public int age;
public string name;
public InfoMsg(int Age, string Name)
{
this.age = Age;
this.name = Name;
}
}
}
}
三 结果展示: