LINQ系列:Linq to Object分区操作符

  分区是指将一个单一的输入序列划分成两个或多个部分或序列,同时不会对输入元素重排序,返回一个新形成的部分。LINQ分割操作符包括Skip、SkipWhile、Take和TakeWhile。

1. Skip

  Skip操作符会跳过一些元素到达序列中的一个指定的位置,将会略过特定数目的若干元素并且返回其余的元素。

1>. 原型定义

public static IEnumerable<TSource> Skip<TSource>(this IEnumerable<TSource> source, int count);

2>. 示例

int[] fibonacci = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 };
var expr = (from f in fibonacci
            select f).Skip(4);
int[] fibonacci = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 };
var expr = from f in fibonacci
           select f;
expr.Skip(4)
var expr = context.Products
    .Skip(10);

2. SkipWhile

  SkipWhile操作符基于特定的逻辑跳过或略过的元素,只要特定的条件为真就继续略过元素,然后返回余下的元素。

  SkipWhile中的条件只对序列或集合的第一个元素开始验证判断,当序列或集合中有一个元素满足验证条件,则后续的元素则不再进行条件验证。

1>. 原型定义

public static IEnumerable<TSource> SkipWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
public static IEnumerable<TSource> SkipWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);

2>. 示例

int[] fibonacci = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 };
var expr = from f in fibonacci
            select f;
expr.SkipWhile(item => item > 2);
var expr = context.Products
    .SkipWhile(p => p.UnitPrice > 10m);
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 6, 3 };
var expr = numbers.SkipWhile(n => n <= 5);

expr.ToList().ForEach(item =>
{
    Console.Write(item + " ");
});

  执行输出:

6 7 8 9 0 6 3

3. Take

  Take操作符返回某个序列中连续的元素子序列,子序列开始与序列的开头,结束于指定的位置。

1>. 原型定义

public static IEnumerable<TSource> Take<TSource>(this IEnumerable<TSource> source, int count);

2>. 示例

int[] fibonacci = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 };
var expr = from f in fibonacci
            select f;
expr.Take(5)
var expr = context.Products
    .Take(5);

4. TakeWhile

  TakeWhile操作符基于特定的逻辑返回元素,并且只要指定的条件为真就继续选取元素,其余元素会被跳过。

  TakeWhile中的条件只对序列或集合的第一个元素开始验证判断,当序列或集合中有一个元素满足验证条件,则后续的元素则不再进行条件验证。

1>. 原型定义

public static IEnumerable<TSource> TakeWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
public static IEnumerable<TSource> TakeWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);

2>. 示例

int[] fibonacci = new int[] { 1, 1, 2, 3, 5, 8, 13, 21 };
var expr = from f in fibonacci
            select f;
expr.TakeWhile(item => item > 2);
var expr = context.Products
    .TakeWhile(p => p.UnitPrice > 10m);

 

int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 6, 3 };
var expr = numbers.TakeWhile(n => n <= 5);

expr.ToList().ForEach(item =>
{
    Console.Write(item + " ");
});

  运行输出:

1 2 3 4 5
posted @ 2014-10-22 23:38  libingql  阅读(436)  评论(0编辑  收藏  举报