BinaryFormat.Choice

Binary

Returns a binary format that chooses the next binary format based on a value that has already been read.

Examples on this page use shared sample tables. View them to understand the input data before reading the examples below.

Syntax

BinaryFormat.Choice(binaryFormat as function, chooseFunction as function, optional type as nullable type, optional combineFunction as nullable function) as function

Parameters

NameTypeRequiredDescription
binaryFormatfunctionYesThe binary format used to read the initial value that determines the choice.
chooseFunctionfunctionYesA function that receives the initial value and returns a second binary format to use for reading the next value.
typenullable typeNoThe expected type of binary format returned by the choice function. Can be type any, type list, or type binary. Using type list or type binary may enable streaming.
combineFunctionnullable functionNoA function that receives both the first and second values and returns a combined result. If not specified, the second value is returned.

Return Value

functionA binary format function that dynamically selects parsing logic based on a previously read value.

Remarks

BinaryFormat.Choice returns a binary format that dynamically determines how to parse binary data based on an initial value. It works in stages:

1. The binaryFormat parameter reads an initial value from the binary stream. 2. That value is passed to chooseFunction, which inspects it and returns a second binary format. 3. The second binary format reads the next value from the stream. 4. If combineFunction is provided, both values are passed to it and the combined result is returned. Otherwise, only the second value is returned.

The optional type parameter (type any, type list, or type binary) hints at the return type of the choice function. Using type list or type binary may allow the system to return streaming values instead of buffered ones, reducing memory usage.

This is essential for parsing binary formats where the structure depends on header values, type tags, or length prefixes.

Examples

Example 1: Read a list of bytes with a length prefix

let
    binaryData = #binary({2, 3, 4, 5}),
    listFormat = BinaryFormat.Choice(
        BinaryFormat.Byte,
        (length) => BinaryFormat.List(BinaryFormat.Byte, length)
    )
in
    listFormat(binaryData)

Example 2: Preserve the first value using a record

let
    binaryData = #binary({2, 3, 4, 5}),
    listFormat = BinaryFormat.Choice(
        BinaryFormat.Byte,
        (length) => BinaryFormat.Record([
            length = length,
            list = BinaryFormat.List(BinaryFormat.Byte, length)
        ])
    )
in
    listFormat(binaryData)

Compatibility

Power BI Desktop Power BI Service Excel Desktop Excel Online Dataflows Fabric Notebooks