Seq.groupBy<'T,'Key> Function (F#)

Applies a key-generating function to each element of a sequence and yields a sequence of unique keys and a sequence of all elements that have each key.

Namespace/Module Path: Microsoft.FSharp.Collections.Seq

Assembly: FSharp.Core (in FSharp.Core.dll)

// Signature:
Seq.groupBy : ('T -> 'Key) -> seq<'T> -> seq<'Key * seq<'T>> (requires equality)

// Usage:
Seq.groupBy projection source

Parameters

  • projection
    Type: 'T -> 'Key

    A function that transforms an element of the sequence into a comparable key.

  • source
    Type: seq<'T>

    The input sequence.

Return Value

A sequence of tuples where each tuple contains the unique key and a sequence of all the elements that match the key.

Remarks

This function returns a sequence that traverses the whole initial sequence as soon as that sequence is iterated. As a result this function should not be used with large or infinite sequences. The function makes no assumption on the ordering of the original sequence.

This function is named GroupBy in compiled assemblies. If you are accessing the function from a language other than F#, or through reflection, use this name.

Example

The following example demonstrates the use of Seq.groupBy to group the odd and even numbers in a sequence into two separate sequences.

let sequence = seq { 1 .. 100 }
let printSeq seq1 = Seq.iter (printf "%A ") seq1; printfn ""
let sequences3 = Seq.groupBy (fun index ->
    if (index % 2 = 0) then 0 else 1) sequence
sequences3 |> printSeq
(1, seq [1; 3; 5; 7; ...]) (0, seq [2; 4; 6; 8; ...]) 

Platforms

Windows 7, Windows Vista SP2, Windows XP SP3, Windows XP x64 SP2, Windows Server 2008 R2, Windows Server 2008 SP2, Windows Server 2003 SP2

Version Information

F# Runtime

Supported in: 2.0, 4.0

Silverlight

Supported in: 3

See Also

Reference

Collections.Seq Module (F#)

Microsoft.FSharp.Collections Namespace (F#)