Skip to content

ChunkBy

Eugene Sadovoi edited this page Jul 27, 2016 · 3 revisions

Groups results by contiguous keys.

Syntax

ChunkBy(keySelect[[, elementSelector], resultSelector])

Parameters

keySelect

A function to extract a key from an element:
TKey keySelect(TSource[, index])

elementSelector

A transform function to produce a result element value from each element:
TElement elementSelector(TSource)

resultSelector

A function to transform the final accumulator value into the result value:
TResult resultSelector(TKey, Iterable<TElement>)

Return Value

An Enumerable that contains grouped elements from the source sequence.

Remarks

Example

The following example shows how to group elements into chunks that represent subsequences of contiguous keys. For example, assume that you are given the following sequence of key-value pairs:

Key Value
A We
A think
A that
B Linq
C is
A really
B cool
B !
var phrase = [
    { key: "A", value: "We" },
    { key: "A", value: "think" },
    { key: "A", value: "that" },
    { key: "B", value: "Linq" },
    { key: "C", value: "is" },
    { key: "A", value: "really" },
    { key: "B", value: "cool" },
    { key: "B", value: "!" }
]

var enumerable = Enumerable.asEnumerable(phrase);
var keySelect = function (item){ return item.key; };
var elementSelector = function (item){ return item.value; };
var resultSelector = function (key, element){ return element; };

var result = enumerable.ChunkBy(keySelect, elementSelector, resultSelector)
                       .ToArray();
/*
The following groups will be created in this order:

1. We, think, that
2. Linq
3. is
4. really
5. cool, !
*/

Try it out

Clone this wiki locally