1、Take操作符
Take
操作符用于从输入序列中返回指定数量的元素,常用于分页。
例如,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
List<People> pList = new List<People>();
People p1 = new People(1, "C", 4);
People p2 = new People(1, "Java", 7);
People p3 = new People(1, "Python", 11);
pList.Add(p1);
pList.Add(p2);
pList.Add(p3);
IEnumerable<People> newList = pList.Take(2); //只取前两个结果
foreach (var item in newList)
{
Console.WriteLine(item.Name);
}
Console.ReadKey();
}
}
public class People
{
public People(int id, string name, int age)
{
this.Id = id;
this.Name = name;
this.Age = age;
}
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}
}
2、TakeWhile操作符
TakeWhile
操作符用于从输入序列中返回指定数量且满足一定条件的元素。
当TakeWhile
操作符被调用时,会将source
序列中的每一个元素顺序传递给委托predicate
,只有那些使得predicate
返回值为true
的元素才会被添加到结果序列中。要特别注意的是,当TakeWhile
操作符在查找过程中,遇到第一个返回false
的元素就会立即停止执行,跳出,无论后面还有没有符合条件的元素,即使后面有符合条件的元素也不会获取。对于第二个扩展方法,委托里面含有一个int
类型的参数,该参数代表集合的下标,可以依据此进行一些据下标操作的逻辑。
例如,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
List<People> pList = new List<People>();
People p1 = new People(1, "C", 6);
People p2 = new People(1, "C#", 11);
People p3 = new People(1, "Java", 8);
People p4 = new People(1, "Python", 15);
pList.Add(p1);
pList.Add(p2);
pList.Add(p3);
pList.Add(p4);
IEnumerable<People> newList = pList.TakeWhile(p => p.Age<11);
foreach (var item in newList)
{
Console.WriteLine(item.Name);
}
Console.WriteLine();
IEnumerable<People> newList1 = pList.TakeWhile((p,i) => p.Age<12 && i<2); //p.Age小于12且下标小于2
foreach (People p in newList1)
{
Console.WriteLine(p.Name);
}
Console.ReadKey();
}
}
public class People
{
public People(int id, string name, int age)
{
this.Id = id;
this.Name = name;
this.Age = age;
}
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
public int Age
{
get;
set;
}
}
}
注意:Where和TakeWhile的区别是,Where会选取所有满足条件的集合,而TakeWhile会选取满足条件的集合,一旦遇到不满足条件的会中止搜索。