BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

LINQ
.NET 3.5+

LINQ Partitioning

The tenth part of the LINQ to Objects tutorial examines partitioning of collections using LINQ. Several standard query operators are provided that break a collection of data into two sections and return one of those parts as an enumerable object.

SkipWhile

SkipWhile is the opposite of TakeWhile. Again a predicate is specified but this time items that meet the condition are skipped. When an item is encountered that causes the predicate to return false, this item and all that follow it are returned.

int pageSize = 3;
int page = 2;
var partitioned = fruit.SkipWhile(s => s.Length < 10);

/* RESULTS

Elderberry
Grape
Kiwi
Lemon
Melon
Orange

*/

Partitioning with Query Expression Syntax

You can use partitioning with queries written using query expression syntax. However, there are no specific clauses for partitioning. Instead, you can apply the standard query operators to the results of a query. As the query and the partition operators will generally use deferred execution, this has no impact on performance or memory use.

int pageSize = 3;
int page = 2;
var partitioned =
    (from f in fruit
    select f)
    .Skip((page - 1) * pageSize).Take(pageSize);

/* RESULTS

Damson
Elderberry
Grape

*/
6 September 2010