Partitioning data (C#)
Partitioning in LINQ refers to the operation of dividing an input sequence into two sections, without rearranging the elements, and then returning one of the sections.
The following illustration shows the results of three different partitioning operations on a sequence of characters. The first operation returns the first three elements in the sequence. The second operation skips the first three elements and returns the remaining elements. The third operation skips the first two elements in the sequence and returns the next three elements.
The standard query operator methods that partition sequences are listed in the following section.
Operators
Method names | Description | C# query expression syntax | More information |
---|---|---|---|
Skip | Skips elements up to a specified position in a sequence. | Not applicable. | Enumerable.Skip Queryable.Skip |
SkipWhile | Skips elements based on a predicate function until an element does not satisfy the condition. | Not applicable. | Enumerable.SkipWhile Queryable.SkipWhile |
Take | Takes elements up to a specified position in a sequence. | Not applicable. | Enumerable.Take Queryable.Take |
TakeWhile | Takes elements based on a predicate function until an element does not satisfy the condition. | Not applicable. | Enumerable.TakeWhile Queryable.TakeWhile |
Chunk | Splits the elements of a sequence into chunks of a specified maximum size. | Not applicable. | Enumerable.Chunk Queryable.Chunk |
Example
The Chunk
operator is used to split elements of a sequence based on a given size
.
int chunkNumber = 1;
foreach (int[] chunk in Enumerable.Range(0, 8).Chunk(3))
{
Console.WriteLine($"Chunk {chunkNumber++}:");
foreach (int item in chunk)
{
Console.WriteLine($" {item}");
}
Console.WriteLine();
}
// This code produces the following output:
// Chunk 1:
// 0
// 1
// 2
//
//Chunk 2:
// 3
// 4
// 5
//
//Chunk 3:
// 6
// 7
The preceding C# code:
- Relies on Enumerable.Range(Int32, Int32) to generate a sequence of numbers.
- Applies the
Chunk
operator, splitting the sequence into chunks with a max size of three.
See also
Feedback
Submit and view feedback for