Skip to content

GroupBy

Dennis Corvers edited this page Oct 23, 2026 · 2 revisions

Enumerable:groupBy

Groups source values by a key selected for each value.

Syntax

groups = source:groupBy(keySelector, elementSelector)

Parameters

Parameter Type Description
keySelector function(value) Returns the key for the group.
elementSelector function(value) (optional) Projects a value before it is added to its group.

Returns

A deferred Enumerable of key/group pairs. Each group is an array of values or selected elements.

Remarks

Groups are represented as a lookup table; iteration order between groups is unspecified. Group keys must be valid Lua table keys and cannot be nil.

Example

local grouped = LuaQ.from({
    { name = "Ada", role = "mage", team = "North" },
    { name = "Bryn", role = "ranger", team = "South" },
    { name = "Cato", role = "mage", team = "North" },
})
    :groupBy(
        function(player) return player.team end,
        function(player) return player.name end
    )
    :toMap()
-- grouped.North is { "Ada", "Cato" }

See also

GroupByResult · ToLookup · Functions

Clone this wiki locally