Documentation
¶
Index ¶
- Variables
- type Enumerator
- func (q Enumerator[T]) All(predicate func(T) bool) bool
- func (q Enumerator[T]) Any() bool
- func (e Enumerator[T]) AverageFloat(keySelector func(T) float32) (float64, bool)
- func (e Enumerator[T]) AverageFloat64(keySelector func(T) float64) (float64, bool)
- func (e Enumerator[T]) AverageInt(keySelector func(T) int) (float64, bool)
- func (e Enumerator[T]) AverageInt64(keySelector func(T) int64) (float64, bool)
- func (q Enumerator[T]) Concat(second Enumerator[T]) Enumerator[T]
- func (e Enumerator[T]) Contains(value T) bool
- func (q Enumerator[T]) Count() int
- func (e Enumerator[T]) DefaultIfEmpty(defaultValue T) Enumerator[T]
- func (q Enumerator[T]) Distinct() Enumerator[T]
- func (e Enumerator[T]) ElementAt(index int) (T, bool)
- func (q Enumerator[T]) Except(second Enumerator[T]) Enumerator[T]
- func (q Enumerator[T]) FirstOrDefault(defaultValue T) T
- func (q Enumerator[T]) FirstOrNil() *T
- func (q Enumerator[T]) ForEach(action func(T))
- func (q Enumerator[T]) Intersect(second Enumerator[T]) Enumerator[T]
- func (q Enumerator[T]) LastOrDefault(defaultValue T) T
- func (q Enumerator[T]) LastOrNil() *T
- func (q Enumerator[T]) LongCount() int64
- func (e Enumerator[T]) MaxBool(keySelector func(T) bool) (bool, bool)
- func (e Enumerator[T]) MaxBy(cmp comparer.ComparerFunc[T]) (T, bool)
- func (e Enumerator[T]) MaxByte(keySelector func(T) byte) (byte, bool)
- func (e Enumerator[T]) MaxFloat(keySelector func(T) float32) (float32, bool)
- func (e Enumerator[T]) MaxFloat64(keySelector func(T) float64) (float64, bool)
- func (e Enumerator[T]) MaxInt(keySelector func(T) int) (int, bool)
- func (e Enumerator[T]) MaxInt64(keySelector func(T) int64) (int64, bool)
- func (e Enumerator[T]) MaxRune(keySelector func(T) rune) (rune, bool)
- func (e Enumerator[T]) MaxString(keySelector func(T) string) (string, bool)
- func (e Enumerator[T]) MaxTime(keySelector func(T) time.Time) (time.Time, bool)
- func (e Enumerator[T]) MinBool(keySelector func(T) bool) (bool, bool)
- func (e Enumerator[T]) MinBy(cmp comparer.ComparerFunc[T]) (T, bool)
- func (e Enumerator[T]) MinByte(keySelector func(T) byte) (byte, bool)
- func (e Enumerator[T]) MinFloat(keySelector func(T) float32) (float32, bool)
- func (e Enumerator[T]) MinFloat64(keySelector func(T) float64) (float64, bool)
- func (e Enumerator[T]) MinInt(keySelector func(T) int) (int, bool)
- func (e Enumerator[T]) MinInt64(keySelector func(T) int64) (int64, bool)
- func (e Enumerator[T]) MinRune(keySelector func(T) rune) (rune, bool)
- func (e Enumerator[T]) MinString(keySelector func(T) string) (string, bool)
- func (e Enumerator[T]) MinTime(keySelector func(T) time.Time) (time.Time, bool)
- func (e Enumerator[T]) OrderBy(comparer comparer.ComparerFunc[T]) OrderEnumerator[T]
- func (e Enumerator[T]) OrderByDescending(comparer comparer.ComparerFunc[T]) OrderEnumerator[T]
- func (e Enumerator[T]) Single() (T, error)
- func (e Enumerator[T]) SingleBy(comparer comparer.EqualityComparer[T]) (T, error)
- func (e Enumerator[T]) SingleOrDefault(defaultValue T) T
- func (q Enumerator[T]) Skip(n int) Enumerator[T]
- func (q Enumerator[T]) SkipLast(n int) Enumerator[T]
- func (q Enumerator[T]) SkipWhile(predicate func(T) bool) Enumerator[T]
- func (q Enumerator[T]) SumFloat(selector func(T) float32) float32
- func (q Enumerator[T]) SumInt(selector func(T) int) int
- func (q Enumerator[T]) Take(n int) Enumerator[T]
- func (q Enumerator[T]) TakeLast(n int) Enumerator[T]
- func (q Enumerator[T]) TakeWhile(predicate func(T) bool) Enumerator[T]
- func (e Enumerator[T]) ToBatch(batchSize int) [][]T
- func (q Enumerator[T]) ToChannel(bufferSize int) <-chan T
- func (q Enumerator[T]) ToMap() map[T]struct{}
- func (q Enumerator[T]) ToSlice() []T
- func (q Enumerator[T]) Union(second Enumerator[T]) Enumerator[T]
- func (q Enumerator[T]) Where(predicate func(T) bool) Enumerator[T]
- type EnumeratorAny
- func (q EnumeratorAny[T]) All(predicate func(T) bool) bool
- func (q EnumeratorAny[T]) Any() bool
- func (e EnumeratorAny[T]) AverageFloat(keySelector func(T) float32) (float64, bool)
- func (e EnumeratorAny[T]) AverageFloat64(keySelector func(T) float64) (float64, bool)
- func (e EnumeratorAny[T]) AverageInt(keySelector func(T) int) (float64, bool)
- func (e EnumeratorAny[T]) AverageInt64(keySelector func(T) int64) (float64, bool)
- func (q EnumeratorAny[T]) Concat(second EnumeratorAny[T]) EnumeratorAny[T]
- func (e EnumeratorAny[T]) Contains(value T, comparer comparer.EqualityComparer[T]) bool
- func (q EnumeratorAny[T]) Count() int
- func (e EnumeratorAny[T]) DefaultIfEmpty(defaultValue T) EnumeratorAny[T]
- func (q EnumeratorAny[T]) Distinct(comparer comparer.EqualityComparer[T]) EnumeratorAny[T]
- func (e EnumeratorAny[T]) ElementAt(index int) (T, bool)
- func (e EnumeratorAny[T]) Except(second EnumeratorAny[T], comparer comparer.EqualityComparer[T]) EnumeratorAny[T]
- func (q EnumeratorAny[T]) FirstOrDefault(defaultValue T) T
- func (q EnumeratorAny[T]) FirstOrNil() *T
- func (q EnumeratorAny[T]) ForEach(action func(T))
- func (q EnumeratorAny[T]) LastOrDefault(defaultValue T) T
- func (q EnumeratorAny[T]) LastOrNil() *T
- func (q EnumeratorAny[T]) LongCount() int64
- func (e EnumeratorAny[T]) MaxBool(keySelector func(T) bool) (bool, bool)
- func (e EnumeratorAny[T]) MaxBy(cmp comparer.ComparerFunc[T]) (T, bool)
- func (e EnumeratorAny[T]) MaxByte(keySelector func(T) byte) (byte, bool)
- func (e EnumeratorAny[T]) MaxFloat(keySelector func(T) float32) (float32, bool)
- func (e EnumeratorAny[T]) MaxFloat64(keySelector func(T) float64) (float64, bool)
- func (e EnumeratorAny[T]) MaxInt(keySelector func(T) int) (int, bool)
- func (e EnumeratorAny[T]) MaxInt64(keySelector func(T) int64) (int64, bool)
- func (e EnumeratorAny[T]) MaxRune(keySelector func(T) rune) (rune, bool)
- func (e EnumeratorAny[T]) MaxString(keySelector func(T) string) (string, bool)
- func (e EnumeratorAny[T]) MaxTime(keySelector func(T) time.Time) (time.Time, bool)
- func (e EnumeratorAny[T]) MinBool(keySelector func(T) bool) (bool, bool)
- func (e EnumeratorAny[T]) MinBy(cmp comparer.ComparerFunc[T]) (T, bool)
- func (e EnumeratorAny[T]) MinByte(keySelector func(T) byte) (byte, bool)
- func (e EnumeratorAny[T]) MinFloat(keySelector func(T) float32) (float32, bool)
- func (e EnumeratorAny[T]) MinFloat64(keySelector func(T) float64) (float64, bool)
- func (e EnumeratorAny[T]) MinInt(keySelector func(T) int) (int, bool)
- func (e EnumeratorAny[T]) MinInt64(keySelector func(T) int64) (int64, bool)
- func (e EnumeratorAny[T]) MinRune(keySelector func(T) rune) (rune, bool)
- func (e EnumeratorAny[T]) MinString(keySelector func(T) string) (string, bool)
- func (e EnumeratorAny[T]) MinTime(keySelector func(T) time.Time) (time.Time, bool)
- func (e EnumeratorAny[T]) OrderBy(comparer comparer.ComparerFunc[T]) OrderEnumeratorAny[T]
- func (e EnumeratorAny[T]) OrderByDescending(comparer comparer.ComparerFunc[T]) OrderEnumeratorAny[T]
- func (e EnumeratorAny[T]) SingleBy(comparer comparer.EqualityComparer[T]) (T, error)
- func (q EnumeratorAny[T]) Skip(n int) EnumeratorAny[T]
- func (q EnumeratorAny[T]) SkipLast(n int) EnumeratorAny[T]
- func (q EnumeratorAny[T]) SkipWhile(predicate func(T) bool) EnumeratorAny[T]
- func (q EnumeratorAny[T]) SumFloat(selector func(T) float32) float32
- func (q EnumeratorAny[T]) SumInt(selector func(T) int) int
- func (q EnumeratorAny[T]) Take(n int) EnumeratorAny[T]
- func (q EnumeratorAny[T]) TakeLast(n int) EnumeratorAny[T]
- func (q EnumeratorAny[T]) TakeWhile(predicate func(T) bool) EnumeratorAny[T]
- func (e EnumeratorAny[T]) ToBatch(batchSize int) [][]T
- func (q EnumeratorAny[T]) ToChannel(bufferSize int) <-chan T
- func (q EnumeratorAny[T]) ToSlice() []T
- func (q EnumeratorAny[T]) Where(predicate func(T) bool) EnumeratorAny[T]
- type MultipleElementsError
- type NoElementsError
- type OrderEnumerator
- func (o OrderEnumerator[T]) Contains(value T) bool
- func (o OrderEnumerator[T]) Distinct() Enumerator[T]
- func (o OrderEnumerator[T]) ElementAt(index int) (T, bool)
- func (o OrderEnumerator[T]) FirstOrDefault(defaultValue T) T
- func (o OrderEnumerator[T]) FirstOrNil() *T
- func (o OrderEnumerator[T]) LastOrDefault(defaultValue T) T
- func (o OrderEnumerator[T]) LastOrNil() *T
- func (o OrderEnumerator[T]) Single() (T, error)
- func (o OrderEnumerator[T]) SingleBy(comparer comparer.EqualityComparer[T]) (T, error)
- func (o OrderEnumerator[T]) SingleOrDefault(defaultValue T) T
- func (o OrderEnumerator[T]) Skip(n int) Enumerator[T]
- func (o OrderEnumerator[T]) SkipLast(n int) Enumerator[T]
- func (o OrderEnumerator[T]) SkipWhile(predicate func(T) bool) Enumerator[T]
- func (o OrderEnumerator[T]) Take(n int) Enumerator[T]
- func (o OrderEnumerator[T]) TakeLast(n int) Enumerator[T]
- func (o OrderEnumerator[T]) TakeWhile(predicate func(T) bool) Enumerator[T]
- func (o OrderEnumerator[T]) ThenBy(comparer comparer.ComparerFunc[T]) OrderEnumerator[T]
- func (o OrderEnumerator[T]) ThenByDescending(comparer comparer.ComparerFunc[T]) OrderEnumerator[T]
- func (e OrderEnumerator[T]) ToBatch(batchSize int) [][]T
- func (o OrderEnumerator[T]) ToChannel(bufferSize int) <-chan T
- func (o OrderEnumerator[T]) ToMap() map[T]struct{}
- func (o OrderEnumerator[T]) ToSlice() []T
- type OrderEnumeratorAny
- func (o OrderEnumeratorAny[T]) Contains(value T, comparer comparer.EqualityComparer[T]) bool
- func (o OrderEnumeratorAny[T]) Distinct(comparer comparer.EqualityComparer[T]) EnumeratorAny[T]
- func (o OrderEnumeratorAny[T]) ElementAt(index int) (T, bool)
- func (o OrderEnumeratorAny[T]) FirstOrDefault(defaultValue T) T
- func (o OrderEnumeratorAny[T]) FirstOrNil() *T
- func (o OrderEnumeratorAny[T]) LastOrDefault(defaultValue T) T
- func (o OrderEnumeratorAny[T]) LastOrNil() *T
- func (o OrderEnumeratorAny[T]) SingleBy(comparer comparer.EqualityComparer[T]) (T, error)
- func (o OrderEnumeratorAny[T]) Skip(n int) EnumeratorAny[T]
- func (o OrderEnumeratorAny[T]) SkipLast(n int) EnumeratorAny[T]
- func (o OrderEnumeratorAny[T]) SkipWhile(predicate func(T) bool) EnumeratorAny[T]
- func (o OrderEnumeratorAny[T]) Take(n int) EnumeratorAny[T]
- func (o OrderEnumeratorAny[T]) TakeLast(n int) EnumeratorAny[T]
- func (o OrderEnumeratorAny[T]) TakeWhile(predicate func(T) bool) EnumeratorAny[T]
- func (o OrderEnumeratorAny[T]) ThenBy(comparer comparer.ComparerFunc[T]) OrderEnumeratorAny[T]
- func (o OrderEnumeratorAny[T]) ThenByDescending(comparer comparer.ComparerFunc[T]) OrderEnumeratorAny[T]
- func (e OrderEnumeratorAny[T]) ToBatch(batchSize int) [][]T
- func (o OrderEnumeratorAny[T]) ToChannel(bufferSize int) <-chan T
- func (o OrderEnumeratorAny[T]) ToSlice() []T
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNoElements is the predefined error instance returned when a sequence contains // no elements. ErrNoElements = &NoElementsError{ message: "sequence contains no elements", } // ErrMultipleElements is the predefined error instance returned when a sequence // contains more than one element, but exactly one was expected. ErrMultipleElements = &MultipleElementsError{ message: "sequence contains more than one element", } )
Functions ¶
This section is empty.
Types ¶
type Enumerator ¶
type Enumerator[T comparable] func(yield func(T) bool)
Enumerator represents a sequence of values that can be iterated over using Go's range loop syntax (Go 1.22+ range-over-func feature). The iteration can be stopped early by the consumer returning false from the yield function.
Type Parameters:
T - the type of values to enumerate (must be comparable)
Notes:
- Thread safety depends on the implementation
- Designed to work with Go 1.22+ range-over-func feature
func Empty ¶
func Empty[T comparable]() Enumerator[T]
Empty returns an empty enumerator of type T that yields no values.
The returned Enumerator[T] will immediately terminate any range loop without executing the loop body, as there are no values to enumerate.
Returns:
An empty Enumerator[T] that can be used in range loops (Go 1.22+).
Notes:
- Can represent "no results" in a type-safe way
- Works with any comparable type T
func FromChannel ¶
func FromChannel[T comparable](ch <-chan T) Enumerator[T]
FromChannel creates an Enumerator[T] that yields values received from a channel. The enumeration continues until the channel is closed or the consumer stops iteration.
The enumerator will:
- Yield each value received from the channel in order
- Terminate when the channel is closed
- Support early termination when the consumer returns false
Parameters:
ch - the source channel to enumerate (read-only)
Returns:
An Enumerator[T] that iterates over channel values
Notes:
- The enumerator will block waiting for new values when channel is empty
- If the channel is never closed, iteration may hang indefinitely
- Safe for nil channels (will act like closed channels, producing no values)
- Channel receive operations occur during enumeration (not beforehand)
- The channel should only be read through the enumerator
func FromSlice ¶
func FromSlice[T comparable](items []T) Enumerator[T]
FromSlice creates an Enumerator[T] that yields all elements from the input slice in order.
The enumerator will produce exactly len(items) values, one for each element in the original slice, preserving their original order. The iteration can be stopped early by the consumer.
Parameters:
items - slice of elements to enumerate (elements must be comparable)
Returns:
An Enumerator[T] that iterates over the slice elements
Notes:
- The slice is captured by reference (modifications will affect iteration)
- For empty slices, produces no values (like Empty())
- Safe for nil slices (treated as empty)
- Preserves the original element order
func Range ¶
func Range(start, count int) Enumerator[int]
Range generates a sequence of consecutive integers starting at 'start', producing exactly 'count' values in ascending order (with step +1).
Parameters:
start - initial value of the sequence (inclusive) count - number of values to generate (must be non-negative)
Returns:
An Enumerator[int] that can be used in range loops.
Notes:
- For count = 0, produces an empty sequence (no iterations)
- For count < 0, behavior is undefined (should be avoided)
func Repeat ¶
func Repeat[T comparable](item T, count int) Enumerator[T]
Repeat generates a sequence containing the same item repeated 'count' times.
Parameters:
item - value to repeat (any comparable type) count - number of repetitions (must be non-negative)
Returns:
An Enumerator[T] that can be used in range loops.
Notes:
- For count = 0, produces an empty sequence (no iterations)
- For count < 0, behavior is undefined (should be avoided)
- Works with any comparable type T (int, string, structs etc.)
func (Enumerator[T]) All ¶
func (q Enumerator[T]) All(predicate func(T) bool) bool
All determines whether all elements in the enumeration satisfy a predicate. Returns true if every element matches the predicate, or if the enumeration is empty.
The method will:
- Apply the predicate to each element in the enumeration
- Return false immediately when the first non-matching element is found
- Return true if all elements match or if there are no elements
- Short-circuit evaluation (stops at first false result)
Parameters:
predicate - a function that takes an element and returns true/false
Returns:
true if all elements satisfy the predicate or enumeration is empty false if at least one element does not satisfy the predicate
Notes:
- For empty enumerations, returns true (vacuous truth)
- For nil enumerators, returns true (consistent with empty behavior)
- Uses short-circuit evaluation for performance
- The predicate function should be pure (no side effects)
- Stops enumeration as soon as a non-matching element is found
func (Enumerator[T]) Any ¶
func (q Enumerator[T]) Any() bool
Any determines whether an enumeration contains any elements. This operation is useful for checking if a sequence is non-empty.
The any operation will:
- Return true if the enumeration contains at least one element
- Return false if the enumeration is empty or nil
- Stop enumeration immediately after finding the first element
- Handle nil enumerators gracefully
Returns:
true if the enumeration contains any elements, false otherwise
Notes:
- If the enumerator is nil, returns false
- If the enumeration is empty, returns false
- Lazy evaluation stops immediately after finding the first element
- This is a terminal operation that materializes the enumeration
- Very efficient - O(1) time complexity for non-empty enumerations
- No elements are buffered - memory efficient
func (Enumerator[T]) AverageFloat ¶ added in v1.25.3
func (e Enumerator[T]) AverageFloat(keySelector func(T) float32) (float64, bool)
AverageFloat returns the arithmetic mean of float32 values extracted from elements of the enumeration using a key selector function. This operation is useful for calculating the average numeric value derived from complex elements.
The AverageFloat operation will:
- Apply the keySelector function to each element to extract a float32 value
- Calculate the sum of all extracted float32 values
- Divide the sum by the count of elements to compute the arithmetic mean
- Return the average as float64 and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts a float32 key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The arithmetic mean of extracted float32 values as float64 and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to calculate the sum and count. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it must process the entire enumeration, which may trigger upstream operations.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Returns float64 for higher precision in result
- For empty enumerations, no division by zero occurs (returns false)
- To calculate average of other numeric types, use AverageInt, AverageInt64, or AverageFloat64
func (Enumerator[T]) AverageFloat64 ¶ added in v1.25.3
func (e Enumerator[T]) AverageFloat64(keySelector func(T) float64) (float64, bool)
AverageFloat64 returns the arithmetic mean of float64 values extracted from elements of the enumeration using a key selector function. This operation is useful for calculating the average numeric value derived from complex elements.
The AverageFloat64 operation will:
- Apply the keySelector function to each element to extract a float64 value
- Calculate the sum of all extracted float64 values
- Divide the sum by the count of elements to compute the arithmetic mean
- Return the average as float64 and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts a float64 key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The arithmetic mean of extracted float64 values as float64 and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to calculate the sum and count. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it must process the entire enumeration, which may trigger upstream operations.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- For empty enumerations, no division by zero occurs (returns false)
- To calculate average of other numeric types, use AverageInt, AverageInt64, or AverageFloat
func (Enumerator[T]) AverageInt ¶ added in v1.25.3
func (e Enumerator[T]) AverageInt(keySelector func(T) int) (float64, bool)
AverageInt returns the arithmetic mean of integer values extracted from elements of the enumeration using a key selector function. This operation is useful for calculating the average numeric value derived from complex elements.
The AverageInt operation will:
- Apply the keySelector function to each element to extract an int value
- Calculate the sum of all extracted integer values
- Divide the sum by the count of elements to compute the arithmetic mean
- Return the average as float64 and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts an int key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The arithmetic mean of extracted integer values as float64 and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to calculate the sum and count. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it must process the entire enumeration, which may trigger upstream operations.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Returns float64 to accommodate fractional results from integer division
- Uses int64 internally to prevent integer overflow during summation
- For empty enumerations, no division by zero occurs (returns false)
- To calculate average of other numeric types, use AverageInt64, AverageFloat, or AverageFloat64
func (Enumerator[T]) AverageInt64 ¶ added in v1.25.3
func (e Enumerator[T]) AverageInt64(keySelector func(T) int64) (float64, bool)
AverageInt64 returns the arithmetic mean of int64 values extracted from elements of the enumeration using a key selector function. This operation is useful for calculating the average numeric value derived from complex elements.
The AverageInt64 operation will:
- Apply the keySelector function to each element to extract an int64 value
- Calculate the sum of all extracted int64 values
- Divide the sum by the count of elements to compute the arithmetic mean
- Return the average as float64 and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts an int64 key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The arithmetic mean of extracted int64 values as float64 and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to calculate the sum and count. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it must process the entire enumeration, which may trigger upstream operations.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Returns float64 to accommodate fractional results from integer division
- Uses float64 internally to handle large int64 values and prevent overflow
- For empty enumerations, no division by zero occurs (returns false)
- To calculate average of other numeric types, use AverageInt, AverageFloat, or AverageFloat64
func (Enumerator[T]) Concat ¶
func (q Enumerator[T]) Concat(second Enumerator[T]) Enumerator[T]
Concat combines two enumerations into a single enumeration. The resulting enumeration yields all elements from the first enumeration, followed by all elements from the second enumeration.
The concatenation will:
- Yield all elements from the first enumeration in order
- Then yield all elements from the second enumeration in order
- Handle nil enumerators gracefully (treated as empty)
- Support early termination when consumer returns false
Parameters:
second - the enumerator to concatenate after the current one
Returns:
A new Enumerator[T] that yields elements from both enumerations in sequence
Notes:
- Nil enumerators are treated as empty (no elements yielded)
- Both enumerations are consumed in order during iteration
- If the first enumeration is infinite, second will never be reached
- Lazy evaluation - elements are produced on-demand during iteration
- No elements are buffered - memory efficient
- Safe for use with any combination of nil and non-nil enumerators
func (Enumerator[T]) Contains ¶ added in v1.25.6
func (e Enumerator[T]) Contains(value T) bool
Contains determines whether a sequence contains a specified element using direct equality comparison. This operation is useful when you need to check for the existence of a specific value in the sequence.
The Contains operation will:
- Return true if the sequence contains an element equal to the specified value
- Return false if the sequence does not contain the specified value
- Return false if the enumerator is nil
- Process elements sequentially until the element is found or sequence ends
- Use direct equality comparison (==) for optimal performance
Parameters:
value - the value to locate in the sequence
Returns:
true if the sequence contains an element equal to the specified value, false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the sequence until the element is found or sequence ends.
⚠️ Memory note: This operation does not buffer elements and requires zero memory allocations.
Notes:
- Uses direct equality comparison (==) for maximum performance
- If enumerator is nil, returns false immediately
- Processes elements sequentially with early termination when element is found
- No elements are buffered - memory efficient
- This is a terminal operation that materializes the enumeration
- Zero allocations for all operations
- Common use cases include membership testing, validation, conditional logic
func (Enumerator[T]) Count ¶
func (q Enumerator[T]) Count() int
Count returns the number of elements in an enumeration. This operation is useful for determining the size of a sequence.
The count operation will:
- Iterate through all elements in the enumeration
- Count each element encountered
- Return the total count
- Handle nil enumerators gracefully
Returns:
The number of elements in the enumeration (0 for empty or nil enumerations)
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to count all elements. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it must process the entire enumeration, which may trigger upstream operations.
Notes:
- If the enumerator is nil, returns 0
- If the enumeration is empty, returns 0
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(1) - constant space usage
- All elements are processed, even if consumer wants to stop early
func (Enumerator[T]) DefaultIfEmpty ¶ added in v1.25.2
func (e Enumerator[T]) DefaultIfEmpty(defaultValue T) Enumerator[T]
DefaultIfEmpty returns an enumeration that contains the elements of the current enumeration, or a single default value if the current enumeration is empty.
The resulting enumeration will:
- Yield all elements from the current enumeration if it contains any elements
- Yield exactly one element (the specified default value) if the current enumeration is empty
- Handle nil enumerators gracefully (treated as empty, yields default value)
- Support early termination when consumer returns false
Parameters:
defaultValue - the value to yield if the current enumeration contains no elements
Returns:
A new Enumerator[T] that yields either the original elements or the default value
Notes:
- Nil enumerators are treated as empty enumerations
- If the current enumeration yields at least one element, the default value is never yielded
- Even if enumeration is terminated early (yield returns false), default value is not added if at least one element was processed
- Lazy evaluation - elements are produced on-demand during iteration
- No elements are buffered - memory efficient
- Safe for use with nil enumerators
func (Enumerator[T]) Distinct ¶
func (q Enumerator[T]) Distinct() Enumerator[T]
Distinct returns an enumerator that yields only unique elements from the original enumeration. Each element appears only once in the result, regardless of how many times it appears in the source.
The distinct operation will:
- Yield each unique element exactly once
- Preserve the order of first occurrence of each element
- Use equality comparison (==) to determine uniqueness
- Support early termination when consumer returns false
Returns:
An Enumerator[T] that yields unique elements in order of first appearance
⚠️ Performance note: This operation buffers all unique elements encountered so far in memory. For enumerations with many unique elements, memory usage can become significant. The operation is not memory-bounded.
Notes:
- Requires T to be comparable (supports == operator)
- Uses map[T]bool internally for tracking seen elements
- Memory usage grows with number of unique elements
- For nil enumerators, returns empty enumerator
- Lazy evaluation - elements processed during iteration
- Elements are compared using Go's built-in equality
func (Enumerator[T]) ElementAt ¶ added in v1.25.5
func (e Enumerator[T]) ElementAt(index int) (T, bool)
ElementAt returns the element at the specified index in the sequence. This operation is useful when you need to access an element at a specific position without iterating through the entire sequence.
The ElementAt operation will:
- Return the element at the specified zero-based index and true if found
- Return the zero value of T and false if index is negative
- Return the zero value of T and false if index is beyond the sequence bounds
- Return the zero value of T and false if the enumerator is nil
- Process elements sequentially until the specified index is reached
Parameters:
index - the zero-based index of the element to retrieve
Returns:
The element at the specified index and true if found, zero value of T and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the sequence until the specified index is reached. Time complexity: O(n) where n is index + 1.
⚠️ Memory note: This operation does not buffer elements, only tracks current position.
Notes:
- Index must be non-negative (negative indices return zero value and false)
- If index is beyond sequence bounds, returns zero value and false
- If enumerator is nil, returns zero value and false
- Processes elements sequentially - early termination when index is found
- No elements are buffered - memory efficient
- This is a terminal operation that materializes the enumeration
func (Enumerator[T]) Except ¶
func (q Enumerator[T]) Except(second Enumerator[T]) Enumerator[T]
Except returns an enumerator that yields elements from the first enumeration that are not present in the second enumeration. This is equivalent to set difference operation (first - second).
The except operation will:
- Yield elements that exist in the first enumeration but not in the second
- Remove duplicates from the result (each element appears only once)
- Preserve the order of first occurrence from the first enumeration
- Handle nil enumerators gracefully
Parameters:
second - the enumerator containing elements to exclude
Returns:
An Enumerator[T] that yields elements from first enumeration not in second
⚠️ Performance note: This operation completely buffers the `second` enumerator into memory (creates a map for fast lookup). For large second enumerations, this may consume significant memory. The memory usage is proportional to the number of unique elements in the second enumerator.
Notes:
- Requires T to be comparable (supports == operator)
- Uses map[T]bool internally for efficient lookup
- Result contains only unique elements (duplicates removed)
- For nil first enumerator, returns empty enumeration
- For nil second enumerator, returns distinct elements from first
- Lazy evaluation - elements processed during iteration
- Memory usage depends on size of second enumeration and unique elements in first
func (Enumerator[T]) FirstOrDefault ¶
func (q Enumerator[T]) FirstOrDefault(defaultValue T) T
FirstOrDefault returns the first element of an enumeration, or a default value if the enumeration is empty or nil.
The first or default operation will:
- Return the first element from the enumeration if it exists
- Return the provided default value if the enumeration is empty or nil
- Stop enumeration immediately after finding the first element
- Handle nil enumerators gracefully
Parameters:
defaultValue - the value to return if the enumeration is empty or nil
Returns:
The first element of the enumeration, or the default value if enumeration is empty
Notes:
- If the enumerator is nil, returns the defaultValue
- If the enumeration is empty, returns the defaultValue
- Lazy evaluation stops immediately after finding the first element
- This is a terminal operation that materializes the enumeration
- Very efficient - O(1) time complexity for non-empty enumerations
- No elements are buffered - memory efficient
- Unlike FirstOrNil(), this method returns the value directly, not a pointer
- Safe for all types including those with zero values like 0, "", false, etc.
- When using zero value as default, consider using FirstOrNil() for distinction
func (Enumerator[T]) FirstOrNil ¶
func (q Enumerator[T]) FirstOrNil() *T
FirstOrNil returns a pointer to the first element of an enumeration. This operation is useful for getting the first element when it exists, with the ability to distinguish between "no elements" and "zero value" cases.
The first operation will:
- Return a pointer to the first element if the enumeration contains elements
- Return nil if the enumeration is empty or nil
- Stop enumeration immediately after finding the first element
- Handle nil enumerators gracefully
Returns:
A pointer to the first element, or nil if enumeration is empty or nil
Notes:
- If the enumerator is nil, returns nil
- If the enumeration is empty, returns nil
- Lazy evaluation stops immediately after finding the first element
- This is a terminal operation that materializes the enumeration
- Very efficient - O(1) time complexity for non-empty enumerations
- No elements are buffered - memory efficient
- Returns pointer to allow distinction between "no elements" (nil) and "zero value" element
- Safe for all types including those with zero values like 0, "", false, etc.
func (Enumerator[T]) ForEach ¶
func (q Enumerator[T]) ForEach(action func(T))
ForEach executes the specified action for each element in the enumeration. This operation is useful for performing side effects like printing, logging, or modifying external state for each element.
The for each operation will:
- Execute the action function for each element in the enumeration
- Process all elements in the enumeration
- Handle nil enumerators gracefully
- Not return any value (void operation)
Parameters:
action - the action to execute for each element
⚠️ Performance note: This operation must iterate through the entire enumeration, which may be expensive for large enumerations.
⚠️ Side effects warning: The action function may have side effects. Use with caution in functional programming contexts.
Notes:
- If the enumerator is nil, no action is executed
- This is a terminal operation that materializes the enumeration
- All elements are processed regardless of action behavior
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(1) - constant space usage
- The enumeration stops only when exhausted or if upstream operations stop it
- Action function should handle all possible values including zero values
func (Enumerator[T]) Intersect ¶
func (q Enumerator[T]) Intersect(second Enumerator[T]) Enumerator[T]
Intersect returns an enumerator that yields elements present in both enumerations. This is equivalent to set intersection operation (first ∩ second).
The intersect operation will:
- Yield elements that exist in both the first and second enumerations
- Remove duplicates from the result (each element appears only once)
- Preserve the order of first occurrence from the first enumeration
- Handle nil enumerators gracefully
Parameters:
second - the enumerator to intersect with
Returns:
An Enumerator[T] that yields elements present in both enumerations
⚠️ Performance note: The second enumeration is completely loaded into memory to enable fast lookups. Be cautious when using this with very large second enumerations as it may cause high memory usage.
Notes:
- Requires T to be comparable (supports == operator)
- Uses map[T]bool internally for efficient lookup
- Result contains only unique elements (duplicates removed)
- For nil first enumerator, returns empty enumeration
- For nil second enumerator, returns empty enumeration
- Lazy evaluation - elements processed during iteration
- Memory usage depends on size of second enumeration and unique elements in first
- Elements are yielded in order of their first appearance in the first enumeration
func (Enumerator[T]) LastOrDefault ¶
func (q Enumerator[T]) LastOrDefault(defaultValue T) T
LastOrDefault returns the last element of an enumeration, or a default value if the enumeration is empty or nil.
The last or default operation will:
- Iterate through all elements in the enumeration
- Keep track of the most recent element encountered
- Return the last element if enumeration contains elements
- Return the provided default value if the enumeration is empty or nil
- Handle nil enumerators gracefully
Parameters:
defaultValue - the value to return if the enumeration is empty or nil
Returns:
The last element of the enumeration, or the default value if enumeration is empty
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the last element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it must process the entire enumeration, which may trigger upstream operations.
Notes:
- If the enumerator is nil, returns the defaultValue
- If the enumeration is empty, returns the defaultValue
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(1) - constant space usage
- Unlike LastOrNil(), this method returns the value directly, not a pointer
- Safe for all types including those with zero values like 0, "", false, etc.
- When using zero value as default, consider using LastOrNil() for distinction
func (Enumerator[T]) LastOrNil ¶
func (q Enumerator[T]) LastOrNil() *T
LastOrNil returns a pointer to the last element of an enumeration, or nil if the enumeration is empty or nil.
The last or nil operation will:
- Iterate through all elements in the enumeration
- Keep track of the most recent element encountered
- Return a pointer to the last element if enumeration contains elements
- Return nil if the enumeration is empty or nil
- Handle nil enumerators gracefully
Returns:
A pointer to the last element, or nil if enumeration is empty or nil
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the last element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it must process the entire enumeration, which may trigger upstream operations.
Notes:
- If the enumerator is nil, returns nil
- If the enumeration is empty, returns nil
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(1) - constant space usage
- Returns pointer to allow distinction between "no elements" (nil) and "zero value" element
- Safe for all types including those with zero values like 0, "", false, etc.
func (Enumerator[T]) LongCount ¶
func (q Enumerator[T]) LongCount() int64
LongCount returns the number of elements in an enumeration as an int64. This operation is useful for determining the size of large sequences where the count might exceed the range of int.
The long count operation will:
- Iterate through all elements in the enumeration
- Count each element encountered using int64 to prevent overflow
- Return the total count as int64
- Handle nil enumerators gracefully
Returns:
The number of elements in the enumeration as int64 (0 for empty or nil enumerations)
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to count all elements. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it must process the entire enumeration, which may trigger upstream operations.
Notes:
- If the enumerator is nil, returns 0
- If the enumeration is empty, returns 0
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(1) - constant space usage
- In Go, int is platform-dependent (32-bit on 32-bit systems, 64-bit on 64-bit systems)
- Use LongCount when you expect very large collections that might overflow int
func (Enumerator[T]) MaxBool ¶ added in v1.25.2
func (e Enumerator[T]) MaxBool(keySelector func(T) bool) (bool, bool)
MaxBool returns the largest boolean value extracted from elements of the enumeration using a key selector function and natural boolean ordering (false < true). This operation is useful for finding the maximum boolean key derived from complex elements.
The MaxBool operation will:
- Apply the keySelector function to each element to extract a bool value
- Compare extracted keys using natural boolean ordering (true > false)
- Return the largest bool key and true if the enumeration is non-empty
- Return false and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when true is found (since true is the maximum value)
Parameters:
keySelector - a function that extracts a bool key from each element of type T.
Must be non-nil; if nil, the operation returns (false, false).
Returns:
The maximum bool key value extracted from elements and true if found, false and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the maximum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (false, false)
- If keySelector is nil, returns (false, false)
- If the enumeration is empty, returns (false, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same maximal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when true is found (since true > false)
- For large enumerations without true values, all elements may be processed
- To use custom ordering, use MaxBoolBy with a custom comparer
- To get the original element associated with the maximum key, use MaxBy instead
func (Enumerator[T]) MaxBy ¶ added in v1.25.2
func (e Enumerator[T]) MaxBy(cmp comparer.ComparerFunc[T]) (T, bool)
MaxBy returns the largest element in the enumeration according to a custom comparison function. This operation is useful for finding the maximum element based on custom ordering criteria.
The MaxBy operation will:
- Return the largest element and true if the enumeration is non-empty
- Return the zero value of T and false if the enumeration is empty or nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators gracefully
- Use the provided comparer function to determine element ordering
Parameters:
cmp - a ComparerFunc that defines the ordering of elements by returning:
-1 if x < y, 0 if x == y, +1 if x > y
Returns:
The maximum element according to the comparer function and true if found, zero value of T and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the maximum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns zero value and false
- If the enumeration is empty, returns zero value and false
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The comparer function is called for each element pair during processing
- If multiple elements are equally maximal, the first one encountered is returned
- This is a terminal operation that materializes the enumeration
- The comparer function must be consistent and deterministic for correct results
- For large enumerations, consider the performance cost of the comparison operations
- The comparer should satisfy mathematical comparison properties (consistency, antisymmetry, transitivity)
- To find the minimum element, use MinBy instead
func (Enumerator[T]) MaxByte ¶ added in v1.25.2
func (e Enumerator[T]) MaxByte(keySelector func(T) byte) (byte, bool)
MaxByte returns the largest byte value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the maximum numeric byte key derived from complex elements.
The MaxByte operation will:
- Apply the keySelector function to each element to extract a byte value
- Compare extracted keys using natural numeric ordering (0 to 255)
- Return the largest byte key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when 255 is found (since 255 is the maximum value)
Parameters:
keySelector - a function that extracts a byte key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The maximum byte key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that iterates through the enumeration to find the maximum element. Performance is optimized with early termination when 255 is found, but worst-case scenario processes all elements.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same maximal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when 255 is found (since 255 is the maximum byte value)
- For large enumerations without 255 values, all elements may be processed
- To get the original element associated with the maximum key, use MaxBy instead
func (Enumerator[T]) MaxFloat ¶ added in v1.25.2
func (e Enumerator[T]) MaxFloat(keySelector func(T) float32) (float32, bool)
MaxFloat returns the largest float32 value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the maximum numeric float32 key derived from complex elements.
The MaxFloat operation will:
- Apply the keySelector function to each element to extract a float32 value
- Compare extracted keys using natural numeric ordering
- Return the largest float32 key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when +Inf is found (since +Inf is the maximum value)
Parameters:
keySelector - a function that extracts a float32 key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The maximum float32 key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the maximum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same maximal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when +Inf is found (since +Inf is the maximum float32 value)
- For large enumerations without +Inf values, all elements may be processed
- To get the original element associated with the maximum key, use MaxBy instead
func (Enumerator[T]) MaxFloat64 ¶ added in v1.25.2
func (e Enumerator[T]) MaxFloat64(keySelector func(T) float64) (float64, bool)
MaxFloat64 returns the largest float64 value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the maximum numeric float64 key derived from complex elements.
The MaxFloat64 operation will:
- Apply the keySelector function to each element to extract a float64 value
- Compare extracted keys using natural numeric ordering
- Return the largest float64 key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when +Inf is found (since +Inf is the maximum value)
Parameters:
keySelector - a function that extracts a float64 key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The maximum float64 key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the maximum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same maximal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when +Inf is found (since +Inf is the maximum float64 value)
- For large enumerations without +Inf values, all elements may be processed
- To get the original element associated with the maximum key, use MaxBy instead
func (Enumerator[T]) MaxInt ¶ added in v1.25.2
func (e Enumerator[T]) MaxInt(keySelector func(T) int) (int, bool)
MaxInt returns the largest integer value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the maximum numeric key (such as ID, age, price, etc.) derived from complex elements in the sequence.
The MaxInt operation will:
- Apply the keySelector function to each element to extract an int value
- Compare extracted keys using natural numeric ordering (descending)
- Return the largest int key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts an int key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The maximum int key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the maximum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- If multiple elements yield the same maximal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- For large enumerations, consider the performance cost of key extraction
- To get the original element associated with the maximum key, use MaxBy instead
func (Enumerator[T]) MaxInt64 ¶ added in v1.25.2
func (e Enumerator[T]) MaxInt64(keySelector func(T) int64) (int64, bool)
MaxInt64 returns the largest int64 value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the maximum numeric key (such as ID, timestamp, size, etc.) derived from complex elements in the sequence.
The MaxInt64 operation will:
- Apply the keySelector function to each element to extract an int64 value
- Compare extracted keys using natural numeric ordering (descending)
- Return the largest int64 key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts an int64 key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The maximum int64 key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the maximum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- If multiple elements yield the same maximal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- For large enumerations, consider the performance cost of key extraction
- To get the original element associated with the maximum key, use MaxBy instead
func (Enumerator[T]) MaxRune ¶ added in v1.25.2
func (e Enumerator[T]) MaxRune(keySelector func(T) rune) (rune, bool)
MaxRune returns the largest rune value extracted from elements of the enumeration using a key selector function and natural Unicode code point ordering. This operation is useful for finding the maximum Unicode character key derived from complex elements.
The MaxRune operation will:
- Apply the keySelector function to each element to extract a rune value
- Compare extracted keys using natural Unicode code point ordering
- Return the largest rune key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when maximum Unicode code point is found
Parameters:
keySelector - a function that extracts a rune key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The maximum rune key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the maximum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same maximal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when maximum Unicode code point is found
- For large enumerations without maximum values, all elements may be processed
- To get the original element associated with the maximum key, use MaxBy instead
func (Enumerator[T]) MaxString ¶ added in v1.25.2
func (e Enumerator[T]) MaxString(keySelector func(T) string) (string, bool)
MaxString returns the lexicographically largest string value extracted from elements of the enumeration using a key selector function and natural string ordering. This operation is useful for finding the maximum string key derived from complex elements.
The MaxString operation will:
- Apply the keySelector function to each element to extract a string value
- Compare extracted keys using natural lexicographic ordering
- Return the largest string key and true if the enumeration is non-empty
- Return empty string ("") and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts a string key from each element of type T.
Must be non-nil; if nil, the operation returns ("", false).
Returns:
The maximum string key value extracted from elements and true if found,
empty string ("") and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the maximum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns ("", false)
- If keySelector is nil, returns ("", false)
- If the enumeration is empty, returns ("", false)
- Processes elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- If multiple elements yield the same maximal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- For large enumerations, all elements may be processed (no early termination optimization)
- To get the original element associated with the maximum key, use MaxBy instead
func (Enumerator[T]) MaxTime ¶ added in v1.25.2
MaxTime returns the latest time.Time value extracted from elements of the enumeration using a key selector function and natural time ordering. This operation is useful for finding the maximum timestamp key derived from complex elements.
The MaxTime operation will:
- Apply the keySelector function to each element to extract a time.Time value
- Compare extracted keys using natural time ordering
- Return the latest time.Time key and true if the enumeration is non-empty
- Return zero time (time.Time{}) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts a time.Time key from each element of type T.
Must be non-nil; if nil, the operation returns (time.Time{}, false).
Returns:
The maximum time.Time key value extracted from elements and true if found,
zero time (time.Time{}) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the maximum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (time.Time{}, false)
- If keySelector is nil, returns (time.Time{}, false)
- If the enumeration is empty, returns (time.Time{}, false)
- Processes elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- If multiple elements yield the same maximal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- For large enumerations, all elements may be processed (no early termination optimization)
- To get the original element associated with the maximum key, use MaxBy instead
func (Enumerator[T]) MinBool ¶ added in v1.25.2
func (e Enumerator[T]) MinBool(keySelector func(T) bool) (bool, bool)
MinBool returns the smallest boolean value extracted from elements of the enumeration using a key selector function and natural boolean ordering (false < true). This operation is useful for finding the minimum boolean key derived from complex elements.
The MinBool operation will:
- Apply the keySelector function to each element to extract a bool value
- Compare extracted keys using natural boolean ordering (false < true)
- Return the smallest bool key and true if the enumeration is non-empty
- Return false and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when false is found (since false is the minimum value)
Parameters:
keySelector - a function that extracts a bool key from each element of type T.
Must be non-nil; if nil, the operation returns (false, false).
Returns:
The minimum bool key value extracted from elements and true if found, false and false otherwise
⚠️ Performance note: This is a terminal operation that iterates through the enumeration to find the minimum element. Performance is optimized with early termination when false is found, but worst-case scenario processes all elements.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (false, false)
- If keySelector is nil, returns (false, false)
- If the enumeration is empty, returns (false, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same minimal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when false is found (since false < true)
- For large enumerations without false values, all elements may be processed
- To get the original element associated with the minimum key, use MinBy instead
func (Enumerator[T]) MinBy ¶ added in v1.25.2
func (e Enumerator[T]) MinBy(cmp comparer.ComparerFunc[T]) (T, bool)
MinBy returns the smallest element in the enumeration according to a custom comparison function. This operation is useful for finding the minimum element based on custom ordering criteria.
The minby operation will:
- Return the smallest element and true if the enumeration is non-empty
- Return the zero value of T and false if the enumeration is empty or nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators gracefully
- Use the provided comparer function to determine element ordering
Parameters:
cmp - a ComparerFunc that defines the ordering of elements by returning:
-1 if x < y, 0 if x == y, +1 if x > y
Returns:
The minimum element according to the comparer function and true if found, zero value of T and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the minimum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns zero value and false
- If the enumeration is empty, returns zero value and false
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The comparer function is called for each element pair during processing
- If multiple elements are equally minimal, the first one encountered is returned
- This is a terminal operation that materializes the enumeration
- The comparer function must be consistent and deterministic for correct results
- For large enumerations, consider the performance cost of the comparison operations
- The comparer should satisfy mathematical comparison properties (consistency, antisymmetry, transitivity)
func (Enumerator[T]) MinByte ¶ added in v1.25.2
func (e Enumerator[T]) MinByte(keySelector func(T) byte) (byte, bool)
MinByte returns the smallest byte value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the minimum numeric byte key derived from complex elements.
The MinByte operation will:
- Apply the keySelector function to each element to extract a byte value
- Compare extracted keys using natural numeric ordering (0 to 255)
- Return the smallest byte key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when 0 is found (since 0 is the minimum value)
Parameters:
keySelector - a function that extracts a byte key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The minimum byte key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that iterates through the enumeration to find the minimum element. Performance is optimized with early termination when 0 is found, but worst-case scenario processes all elements.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same minimal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when 0 is found (since 0 is the minimum byte value)
- For large enumerations without 0 values, all elements may be processed
- To use custom ordering, use MinByteBy with a custom comparer
- To get the original element associated with the minimum key, use MinBy instead
func (Enumerator[T]) MinFloat ¶ added in v1.25.2
func (e Enumerator[T]) MinFloat(keySelector func(T) float32) (float32, bool)
MinFloat returns the smallest float32 value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the minimum numeric float32 key derived from complex elements.
The MinFloat operation will:
- Apply the keySelector function to each element to extract a float32 value
- Compare extracted keys using natural numeric ordering
- Return the smallest float32 key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when -Inf is found (since -Inf is the minimum value)
Parameters:
keySelector - a function that extracts a float32 key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The minimum float32 key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the minimum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same minimal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when -Inf is found (since -Inf is the minimum float32 value)
- For large enumerations without -Inf values, all elements may be processed
- To get the original element associated with the minimum key, use MinBy instead
func (Enumerator[T]) MinFloat64 ¶ added in v1.25.2
func (e Enumerator[T]) MinFloat64(keySelector func(T) float64) (float64, bool)
MinFloat64 returns the smallest float64 value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the minimum numeric float64 key derived from complex elements.
The MinFloat64 operation will:
- Apply the keySelector function to each element to extract a float64 value
- Compare extracted keys using natural numeric ordering
- Return the smallest float64 key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when -Inf is found (since -Inf is the minimum value)
Parameters:
keySelector - a function that extracts a float64 key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The minimum float64 key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the minimum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same minimal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when -Inf is found (since -Inf is the minimum float64 value)
- For large enumerations without -Inf values, all elements may be processed
- To get the original element associated with the minimum key, use MinBy instead
func (Enumerator[T]) MinInt ¶ added in v1.25.2
func (e Enumerator[T]) MinInt(keySelector func(T) int) (int, bool)
MinInt returns the smallest integer value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the minimum numeric key (such as ID, age, price, etc.) derived from complex elements in the sequence.
The MinInt operation will:
- Apply the keySelector function to each element to extract an int value
- Compare extracted keys using natural numeric ordering (ascending)
- Return the smallest int key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts an int key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The minimum int key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the minimum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- If multiple elements yield the same minimal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- For large enumerations, consider the performance cost of key extraction
- To get the original element associated with the minimum key, use MinBy instead
func (Enumerator[T]) MinInt64 ¶ added in v1.25.2
func (e Enumerator[T]) MinInt64(keySelector func(T) int64) (int64, bool)
MinInt64 returns the smallest int64 value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the minimum numeric key (such as ID, timestamp, size, etc.) derived from complex elements in the sequence.
The MinInt64 operation will:
- Apply the keySelector function to each element to extract an int64 value
- Compare extracted keys using natural numeric ordering (ascending)
- Return the smallest int64 key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts an int64 key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The minimum int64 key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the minimum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- If multiple elements yield the same minimal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- For large enumerations, consider the performance cost of key extraction
- To get the original element associated with the minimum key, use MinBy instead
func (Enumerator[T]) MinRune ¶ added in v1.25.2
func (e Enumerator[T]) MinRune(keySelector func(T) rune) (rune, bool)
MinRune returns the smallest rune value extracted from elements of the enumeration using a key selector function and natural Unicode code point ordering. This operation is useful for finding the minimum Unicode character key derived from complex elements.
The MinRune operation will:
- Apply the keySelector function to each element to extract a rune value
- Compare extracted keys using natural Unicode code point ordering
- Return the smallest rune key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when 0 is found (since 0 is the minimum Unicode code point)
Parameters:
keySelector - a function that extracts a rune key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The minimum rune key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that iterates through the enumeration to find the minimum element. Performance is optimized with early termination when 0 is found (since 0 is the minimum Unicode code point), but worst-case scenario processes all elements.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same minimal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when 0 is found (since 0 is the minimum Unicode code point)
- For large enumerations without 0 values, all elements may be processed
- To get the original element associated with the minimum key, use MinBy instead
func (Enumerator[T]) MinString ¶ added in v1.25.2
func (e Enumerator[T]) MinString(keySelector func(T) string) (string, bool)
MinString returns the lexicographically smallest string value extracted from elements of the enumeration using a key selector function and natural string ordering. This operation is useful for finding the minimum string key derived from complex elements.
The MinString operation will:
- Apply the keySelector function to each element to extract a string value
- Compare extracted keys using natural lexicographic ordering
- Return the smallest string key and true if the enumeration is non-empty
- Return empty string ("") and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when empty string is found
Parameters:
keySelector - a function that extracts a string key from each element of type T.
Must be non-nil; if nil, the operation returns ("", false).
Returns:
The minimum string key value extracted from elements and true if found,
empty string ("") and false otherwise
⚠️ Performance note: This is a terminal operation that iterates through the enumeration to find the minimum element. Performance is optimized with early termination when empty string is found, but worst-case scenario processes all elements.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns ("", false)
- If keySelector is nil, returns ("", false)
- If the enumeration is empty, returns ("", false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same minimal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when empty string is found (since "" < any non-empty string)
- For large enumerations without empty strings, all elements may be processed
- To get the original element associated with the minimum key, use MinBy instead
func (Enumerator[T]) MinTime ¶ added in v1.25.2
MinTime returns the earliest time.Time value extracted from elements of the enumeration using a key selector function and natural time ordering. This operation is useful for finding the minimum timestamp key derived from complex elements.
The MinTime operation will:
- Apply the keySelector function to each element to extract a time.Time value
- Compare extracted keys using natural time ordering
- Return the earliest time.Time key and true if the enumeration is non-empty
- Return zero time (time.Time{}) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when zero time is found
Parameters:
keySelector - a function that extracts a time.Time key from each element of type T.
Must be non-nil; if nil, the operation returns (time.Time{}, false).
Returns:
The minimum time.Time key value extracted from elements and true if found,
zero time (time.Time{}) and false otherwise
⚠️ Performance note: This is a terminal operation that iterates through the enumeration to find the minimum element. Performance is optimized with early termination when zero time is found, but worst-case scenario processes all elements.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (time.Time{}, false)
- If keySelector is nil, returns (time.Time{}, false)
- If the enumeration is empty, returns (time.Time{}, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same minimal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when zero time is found (since time.Time{} is the earliest possible time)
- For large enumerations without zero times, all elements may be processed
- To get the original element associated with the minimum key, use MinBy instead
func (Enumerator[T]) OrderBy ¶ added in v1.25.7
func (e Enumerator[T]) OrderBy(comparer comparer.ComparerFunc[T]) OrderEnumerator[T]
OrderBy sorts the elements of a sequence in ascending order according to a comparer function. This method is the primary sorting operation that establishes the first sorting level.
The OrderBy operation:
- Accumulates sorting rules without immediate execution (lazy evaluation)
- Returns an OrderEnumerator that supports fluent chaining with ThenBy operations
- Uses the provided comparer function to determine element ordering
- Maintains stable sorting (equal elements preserve relative order)
- Works with comparable types using direct comparison
Parameters:
comparer - a ComparerFunc that defines the sort order by comparing two elements of type T
The function should return:
< 0 if first element is less than second
= 0 if elements are equal
> 0 if first element is greater than second
Returns:
An OrderEnumerator[T] that contains the sorted elements and supports further sorting operations
⚠️ Performance note: This is a deferred execution operation that accumulates sorting rules. Actual sorting computation occurs during first enumeration. Time complexity: O(1) for rule accumulation, O(n log n) for actual sorting during enumeration.
Notes:
- This is a lazy operation - no sorting occurs until enumeration begins
- Multiple OrderBy calls overwrite previous sorting rules (use ThenBy for multiple levels)
- The comparer function must be deterministic and consistent
- For subsequent sorting levels, use ThenBy or ThenByDescending
- Works with both comparable and non-comparable types through appropriate comparer functions
- Thread-safe for rule accumulation, but enumeration should be single-threaded
func (Enumerator[T]) OrderByDescending ¶ added in v1.25.7
func (e Enumerator[T]) OrderByDescending(comparer comparer.ComparerFunc[T]) OrderEnumerator[T]
OrderByDescending sorts the elements of a sequence in descending order according to a comparer function. This method is the primary sorting operation that establishes the first sorting level in reverse order.
The OrderByDescending operation:
- Accumulates sorting rules without immediate execution (lazy evaluation)
- Returns an OrderEnumerator that supports fluent chaining with ThenBy operations
- Uses the provided comparer function to determine element ordering (reversed)
- Maintains stable sorting (equal elements preserve relative order)
- Works with comparable types using direct comparison
Parameters:
comparer - a ComparerFunc that defines the sort order by comparing two elements of type T
The function should return:
< 0 if first element is less than second
= 0 if elements are equal
> 0 if first element is greater than second
Note: The final order will be reversed (descending)
Returns:
An OrderEnumerator[T] that contains the sorted elements and supports further sorting operations
⚠️ Performance note: This is a deferred execution operation that accumulates sorting rules. Actual sorting computation occurs during first enumeration. Time complexity: O(1) for rule accumulation, O(n log n) for actual sorting during enumeration.
Notes:
- This is a lazy operation - no sorting occurs until enumeration begins
- Multiple OrderByDescending calls overwrite previous sorting rules (use ThenByDescending for multiple levels)
- The comparer function must be deterministic and consistent
- For subsequent sorting levels, use ThenBy or ThenByDescending
- Works with both comparable and non-comparable types through appropriate comparer functions
- Thread-safe for rule accumulation, but enumeration should be single-threaded
func (Enumerator[T]) Single ¶ added in v1.25.4
func (e Enumerator[T]) Single() (T, error)
Single returns the single element of a sequence using default equality comparison. This operation is useful when you expect exactly one element in the sequence.
The Single operation will:
- Return the single element if the sequence contains exactly one element
- Return an error if the sequence is empty ("sequence contains no elements")
- Return an error if the sequence contains more than one element ("sequence contains more than one element")
- Process elements sequentially until completion or error
- Handle nil enumerators gracefully
Returns:
The single element of the sequence and nil error if successful, zero value of T and error otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the sequence until completion or error. For large sequences with multiple elements, this may process more elements than necessary.
⚠️ Memory note: This operation does not buffer elements, but it may process multiple elements to ensure uniqueness, which may trigger upstream operations.
Notes:
- If the enumerator is nil, returns zero value and error ("sequence contains no elements")
- If the enumeration is empty, returns zero value and error ("sequence contains no elements")
- If the enumeration contains more than one element, returns zero value and error ("sequence contains more than one element")
- Processes elements in the enumeration - O(n) time complexity in worst case
- No elements are buffered - memory efficient
- This is a terminal operation that materializes the enumeration
- Works only with comparable types (no slices, maps, functions in struct fields)
- The type T must be comparable for equality comparison to work
- For large enumerations, all elements may be processed to ensure uniqueness
- This method should be used when you are certain the sequence contains exactly one element
- Common use cases include lookup by unique identifier or configuration validation
func (Enumerator[T]) SingleBy ¶ added in v1.25.4
func (e Enumerator[T]) SingleBy(comparer comparer.EqualityComparer[T]) (T, error)
SingleBy returns the single element of a sequence that satisfies the provided equality comparer. This operation is useful when you expect exactly one element in the sequence and need custom equality logic.
The SingleBy operation will:
- Return the single element if the sequence contains exactly one distinct element according to the comparer
- Return an error if the sequence is empty ("sequence contains no elements")
- Return an error if the sequence contains more than one distinct element according to the comparer
- Process elements sequentially until completion or second distinct element found
- Handle nil enumerators gracefully
Parameters:
comparer - an EqualityComparer that defines when two elements are considered equal
Returns:
The single element of the sequence and nil error if successful, zero value of T and error otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the sequence until completion or second distinct element found. For large sequences with multiple distinct elements, this may process more elements than necessary. Average time complexity: O(n) where n is the number of elements processed.
⚠️ Memory note: This operation buffers elements to perform equality comparison using hash-based lookup. Memory usage depends on the number of distinct elements encountered during processing. Worst case memory complexity: O(n) where n is the number of distinct elements.
Notes:
- If the enumerator is nil, returns zero value and error ("sequence contains no elements")
- If the enumeration is empty, returns zero value and error ("sequence contains no elements")
- If the enumeration contains more than one distinct element, returns zero value and error ("sequence contains more than one element")
- Uses the provided comparer's Equals and GetHashCode methods for efficient element comparison
- Elements are buffered in hash buckets during comparison for efficient duplicate detection
- This is a terminal operation that materializes the enumeration
- Works with any type T (including non-comparable types) when used with appropriate comparer
- The comparer functions must be consistent and deterministic
- For large enumerations, processing stops early when second distinct element is found
- This method should be used when you are certain the sequence contains exactly one distinct element
- Common use cases include lookup by custom equality logic, complex object comparison, or unique constraint validation
func (Enumerator[T]) SingleOrDefault ¶ added in v1.25.4
func (e Enumerator[T]) SingleOrDefault(defaultValue T) T
SingleOrDefault returns the single element of a sequence using default equality comparison, or a specified default value if the sequence is empty.
The SingleOrDefault operation will:
- Return the single element if the sequence contains exactly one element
- Return the specified default value if the sequence is empty (including nil enumerator)
- Return the specified default value if the sequence contains more than one element
- Process elements sequentially until completion or second element found
- Handle nil enumerators gracefully (treated as empty)
Returns:
The single element of the sequence if successful, or the specified default value otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the sequence until completion or second element found. For large sequences with multiple elements, this may process more elements than necessary.
⚠️ Memory note: This operation does not buffer elements, but it may process multiple elements to ensure uniqueness, which may trigger upstream operations.
Notes:
- If the enumerator is nil, returns the specified default value
- If the enumeration is empty, returns the specified default value
- If the enumeration contains more than one element, returns the specified default value
- Processes elements in the enumeration - O(n) time complexity in worst case
- No elements are buffered - memory efficient
- This is a terminal operation that materializes the enumeration
- Works only with comparable types (no slices, maps, functions in struct fields)
- The type T must be comparable for equality comparison to work
- For large enumerations, elements may be processed to detect multiple items
- This method should be used when you expect zero or one element, with fallback for other cases
- Common use cases include optional lookup by unique identifier or configuration with defaults
⚠️ Important: Unlike Single(), this method never returns an error. All error conditions (empty sequence, multiple elements) result in returning the default value. If you need to distinguish between these cases, use Single() instead.
func (Enumerator[T]) Skip ¶
func (q Enumerator[T]) Skip(n int) Enumerator[T]
Skip bypasses a specified number of elements in an enumeration and then yields the remaining elements. This operation is useful for pagination, skipping headers, or bypassing initial elements.
The skip operation will:
- Bypass the first n elements from the enumeration
- Yield all remaining elements in order
- Handle edge cases gracefully (n <= 0, n >= count)
- Support early termination when consumer returns false
Parameters:
n - the number of elements to skip (must be non-negative)
Returns:
An Enumerator[T] that yields elements after skipping the first n elements
Notes:
- If n <= 0, returns the original enumerator unchanged
- If n >= total number of elements, returns an empty enumerator
- If the original enumerator is nil, returns an empty enumerator (not nil)
- Lazy evaluation - elements are processed and skipped during iteration
- No elements are buffered - memory efficient
- Negative values of n are treated as 0
- The enumeration is consumed sequentially, so skipped elements are still processed
func (Enumerator[T]) SkipLast ¶
func (q Enumerator[T]) SkipLast(n int) Enumerator[T]
SkipLast bypasses a specified number of elements at the end of an enumeration and yields the remaining elements. This operation is useful for removing trailing elements like footers, summaries, or fixed-size endings from sequences.
The skip last operation will:
- Buffer elements to track which are the final n elements
- Yield elements only after confirming they are not among the last n
- Handle edge cases gracefully (n <= 0, n >= count)
- Support early termination when consumer returns false
Parameters:
n - the number of elements to skip from the end (must be non-negative)
Returns:
An Enumerator[T] that yields elements except the last n elements
⚠️ Performance note: This operation buffers up to n elements in memory using a circular buffer for efficient memory usage. For large values of n, this may consume significant memory.
⚠️ Evaluation note: This operation is partially lazy - elements are processed as the enumeration proceeds, but the last n elements are buffered and never yielded. The enumeration must progress beyond n elements to yield earlier ones.
Notes:
- If n <= 0, returns the original enumerator unchanged
- If n >= total number of elements, returns an empty enumerator
- If the original enumerator is nil, returns an empty enumerator
- Elements are yielded in order of their appearance in the original enumeration
- Negative values of n are treated as 0
func (Enumerator[T]) SkipWhile ¶
func (q Enumerator[T]) SkipWhile(predicate func(T) bool) Enumerator[T]
SkipWhile bypasses elements in an enumeration as long as a specified condition is true and then yields the remaining elements. This operation is useful for skipping elements until a certain condition is met.
The skip while operation will:
- Bypass elements from the beginning while the predicate returns true
- Once the predicate returns false for an element, yield that element and all subsequent elements
- Support early termination when consumer returns false
Parameters:
predicate - a function that determines whether to skip an element
Returns:
An Enumerator[T] that yields elements after skipping initial elements that match the condition
Notes:
- If the predicate never returns false, returns an empty enumerator
- If the predicate immediately returns false for the first element, returns the original enumerator
- If the original enumerator is nil, returns an empty enumerator
- Lazy evaluation - elements are processed and evaluated during iteration
- No elements are buffered - memory efficient
- The enumeration stops skipping as soon as the first non-matching element is found
- Once skipping stops, all remaining elements are yielded (even if they would match the predicate)
func (Enumerator[T]) SumFloat ¶
func (q Enumerator[T]) SumFloat(selector func(T) float32) float32
SumFloat computes the sum of float32 values obtained by applying a selector function to each element in the enumeration. This operation is useful for calculating totals, aggregates, or numeric summaries with floating-point precision.
The sum float operation will:
- Apply the selector function to each element to extract a float32 value
- Sum all the extracted float32 values
- Return the total sum
- Handle nil enumerators gracefully
Parameters:
selector - a function that extracts a float32 value from each element
Returns:
The sum of all float32 values extracted from the elements
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to sum all values. For large enumerations, this may be expensive.
⚠️ Precision warning: Floating-point arithmetic may introduce small rounding errors. Consider using appropriate rounding for display.
Notes:
- If the enumerator is nil, returns 0
- If the enumeration is empty, returns 0
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(1) - constant space usage
- The enumeration stops only when exhausted or if upstream operations stop it
- Selector function should handle all possible input values safely
- For double precision, consider implementing or using SumFloat64
func (Enumerator[T]) SumInt ¶
func (q Enumerator[T]) SumInt(selector func(T) int) int
SumInt computes the sum of integers obtained by applying a selector function to each element in the enumeration. This operation is useful for calculating totals, aggregates, or numeric summaries.
The sum int operation will:
- Apply the selector function to each element to extract an integer value
- Sum all the extracted integer values
- Return the total sum
- Handle nil enumerators gracefully
Parameters:
selector - a function that extracts an integer value from each element
Returns:
The sum of all integer values extracted from the elements
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to sum all values. For large enumerations, this may be expensive.
⚠️ Overflow warning: Integer overflow may occur with very large sums. Consider using SumInt64 for larger ranges.
Notes:
- If the enumerator is nil, returns 0
- If the enumeration is empty, returns 0
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(1) - constant space usage
- The enumeration stops only when exhausted or if upstream operations stop it
- Selector function should handle all possible input values safely
func (Enumerator[T]) Take ¶
func (q Enumerator[T]) Take(n int) Enumerator[T]
Take returns a specified number of contiguous elements from the start of an enumeration. This operation is useful for pagination, limiting results, or taking samples from sequences.
The take operation will:
- Yield the first n elements from the enumeration
- Stop enumeration once n elements have been yielded
- Handle edge cases gracefully (n <= 0, n >= count)
- Support early termination when consumer returns false
Parameters:
n - the number of elements to take (must be non-negative)
Returns:
An Enumerator[T] that yields at most n elements from the start
Notes:
- If n <= 0, returns an empty enumerator
- If n >= total number of elements, returns all available elements
- If the original enumerator is nil, returns an empty enumerator
- Lazy evaluation - elements are processed and yielded during iteration
- No elements are buffered - memory efficient
- Negative values of n are treated as 0
- Early termination by the consumer stops further enumeration
- The enumeration stops as soon as n elements are yielded or the source is exhausted
func (Enumerator[T]) TakeLast ¶
func (q Enumerator[T]) TakeLast(n int) Enumerator[T]
TakeLast returns a specified number of contiguous elements from the end of an enumeration. This operation is useful for getting the final elements, such as last N records, trailing averages, or end-of-sequence markers.
The take last operation will:
- Buffer elements to track the last n elements seen so far
- Yield the final n elements when enumeration completes
- Handle edge cases gracefully (n <= 0, n >= count)
- Support early termination when consumer returns false
Parameters:
n - the number of elements to take from the end (must be non-negative)
Returns:
An Enumerator[T] that yields the last n elements
⚠️ Performance note: This operation buffers up to n elements in memory to track which elements should be yielded. For large values of n, this may consume significant memory. All elements must be processed before any are yielded.
⚠️ Evaluation note: This operation is not lazy in the traditional sense - the entire source enumeration must be consumed before yielding begins. Elements are yielded in order of their appearance in the original enumeration.
Notes:
- If n <= 0, returns an empty enumerator
- If n >= total number of elements, returns all available elements
- If the original enumerator is nil, returns an empty enumerator
- Negative values of n are treated as 0
- The enumeration stops as soon as the consumer returns false
func (Enumerator[T]) TakeWhile ¶
func (q Enumerator[T]) TakeWhile(predicate func(T) bool) Enumerator[T]
TakeWhile returns elements from an enumeration as long as a specified condition is true. This operation is useful for taking elements until a certain condition is met, such as taking elements while they are valid or within a range.
The take while operation will:
- Yield elements from the start while the predicate returns true
- Stop enumeration as soon as the predicate returns false for an element
- Handle edge cases gracefully (nil enumerator, always false predicate)
- Support early termination when consumer returns false
Parameters:
predicate - a function that determines whether to take an element
Returns:
An Enumerator[T] that yields elements while the condition is true
Notes:
- If the predicate immediately returns false for the first element, returns empty enumerator
- If the predicate never returns false, returns all elements from the enumeration
- If the original enumerator is nil, returns an empty enumerator
- Lazy evaluation - elements are processed and evaluated during iteration
- No elements are buffered - memory efficient
- The enumeration stops as soon as the predicate returns false or consumer returns false
- Once the predicate returns false for any element, no subsequent elements are evaluated
func (Enumerator[T]) ToBatch ¶ added in v1.25.8
func (e Enumerator[T]) ToBatch(batchSize int) [][]T
ToBatch groups elements from an enumeration into batches of specified size and returns them as a slice of slices. This operation is useful for processing large sequences in chunks, implementing pagination, or optimizing batch operations.
The to batch operation will:
- Group consecutive elements into slices of at most batchSize elements
- Return all batches as a slice when enumeration is complete
- Handle edge cases gracefully (batchSize <= 0, empty source)
- Materialize the entire enumeration (terminal operation)
Parameters:
batchSize - the maximum number of elements per batch (must be positive)
Returns:
A slice containing batches of elements, or empty slice if no batches
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to create all batches.
⚠️ Memory note: This operation buffers all elements in memory during processing.
Notes:
- If batchSize <= 0, returns empty slice
- If the original enumerator is nil, returns empty slice
- Last batch may contain fewer elements than batchSize
- Terminal operation - consumes entire enumeration
- Each batch is a separate slice - safe for modification
- No elements are lost - all elements from source are included in batches
func (Enumerator[T]) ToChannel ¶
func (q Enumerator[T]) ToChannel(bufferSize int) <-chan T
ToChannel converts an enumeration to a channel that yields all elements. This operation is useful for converting lazy enumerations into channel-based processing pipelines or for interoperability with goroutines.
The to channel operation will:
- Create a new channel with specified buffer size
- Start a goroutine that iterates through the enumeration
- Send each element to the channel
- Close the channel when enumeration is complete
- Handle nil enumerators gracefully
Parameters:
bufferSize - the buffer size for the returned channel (0 for unbuffered)
Returns:
A read-only channel containing all elements from the enumeration
⚠️ Resource management: This operation starts a goroutine that runs until the enumeration is complete. Always consume all elements or the goroutine may block indefinitely.
⚠️ Blocking behavior: The goroutine will block when trying to send to a full channel if there's no reader. Use appropriate buffer size.
⚠️ Warning: If the returned channel is not fully consumed, the goroutine may leak. Always range over the entire channel or ensure proper cleanup.
Notes:
- If the enumerator is nil, returns a closed channel
- If the enumeration is empty, returns an empty but closed channel
- The goroutine automatically closes the channel when done
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(bufferSize) plus any upstream buffering
- The enumeration runs in a separate goroutine, enabling concurrent processing
func (Enumerator[T]) ToMap ¶
func (q Enumerator[T]) ToMap() map[T]struct{}
ToMap converts an enumeration to a map[T]struct{} for efficient set-like operations. This operation is useful for creating memory-efficient lookup collections or for removing duplicates while materializing an enumeration.
The to map operation will:
- Iterate through all elements in the enumeration
- Add each element as a key in the resulting map with empty struct value
- Automatically remove duplicates (map key uniqueness)
- Return the resulting map
- Handle nil enumerators gracefully by returning an empty map
Returns:
A map[T]struct{} containing all unique elements as keys,
or an empty map if enumerator is nil or enumeration is empty
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration. For large enumerations, this may be expensive.
⚠️ Memory note: This operation buffers all unique elements in memory. The memory usage depends on the number of unique elements.
Notes:
- If the enumerator is nil, returns an empty map (not nil)
- If the enumeration is empty, returns an empty map
- Automatically removes duplicates due to map key uniqueness
- Uses map[T]struct{} for memory efficiency (struct{} takes zero memory)
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(k) where k is the number of unique elements
- Keys in the returned map are the unique elements from the enumeration
- Values in the returned map are empty structs (zero memory footprint)
- Check for element presence using: if _, exists := map[key]; exists { ... }
- More memory-efficient than map[T]bool since struct{} takes no memory
- Always returns a valid map, never nil - safe for immediate use
func (Enumerator[T]) ToSlice ¶
func (q Enumerator[T]) ToSlice() []T
ToSlice converts an enumeration to a slice containing all elements. This operation is useful for materializing lazy enumerations into concrete collections.
The to slice operation will:
- Iterate through all elements in the enumeration
- Collect all elements into a new slice
- Return the slice containing all elements in order
- Handle nil enumerators gracefully
Returns:
A slice containing all elements from the enumeration, or empty slice if enumerator is nil
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to collect all elements. For large enumerations, this may be expensive in both time and memory.
⚠️ Memory note: This operation buffers all elements in memory.
Notes:
- If the enumerator is nil, returns an empty slice (not nil)
- If the enumeration is empty, returns an empty slice
- For very large enumerations, consider processing elements incrementally.
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(n) - allocates memory for all elements
- The enumeration stops only when exhausted or if upstream operations stop it
- Returned slice preserves the order of elements from the enumeration
- Use with caution for infinite or very large enumerations
func (Enumerator[T]) Union ¶
func (q Enumerator[T]) Union(second Enumerator[T]) Enumerator[T]
Union produces the set union of two enumerations by using the default equality comparer. This operation returns unique elements that appear in either enumeration.
The union operation will:
- Yield all unique elements from the first enumeration
- Then yield unique elements from the second enumeration that haven't been seen yet
- Remove duplicates both within each enumeration and between enumerations
- Preserve the order of first occurrence of each element
- Handle nil enumerators gracefully
- Support early termination when consumer returns false
Parameters:
second - the enumerator to union with the current one
Returns:
An Enumerator[T] that yields unique elements from both enumerations
⚠️ Performance note: This operation buffers all unique elements encountered so far in memory. For enumerations with many unique elements, memory usage can become significant. The operation is not memory-bounded.
Notes:
- Requires T to be comparable (supports == operator)
- Uses map[T]bool internally for tracking seen elements
- Memory usage grows with number of unique elements from both enumerations
- For nil enumerators, treats them as empty enumerations
- Lazy evaluation - elements are processed during iteration
- Elements are yielded in order: first unique elements from the first enumeration, then unique elements from the second enumeration that weren't in the first
- Early termination by the consumer stops further enumeration of both sources
Union produces the set union of two enumerations by using the default equality comparer.
func (Enumerator[T]) Where ¶
func (q Enumerator[T]) Where(predicate func(T) bool) Enumerator[T]
Where filters an enumeration based on a predicate function. This operation returns elements that satisfy the specified condition.
The where operation will:
- Apply the predicate function to each element in the enumeration
- Yield only elements for which the predicate returns true
- Preserve the original order of elements that pass the filter
- Handle nil enumerators gracefully
- Support early termination when consumer returns false
Parameters:
predicate - a function that determines whether to include an element
Returns:
An Enumerator[T] that yields elements satisfying the predicate
Notes:
- If the original enumerator is nil, returns an empty enumerator
- Lazy evaluation - elements are processed and filtered during iteration
- No elements are buffered - memory efficient
- The enumeration stops when the source is exhausted or consumer returns false
- Predicate function should be pure (no side effects) for predictable behavior
- Elements for which predicate returns false are simply skipped
type EnumeratorAny ¶
EnumeratorAny represents a sequence of values that can be iterated over using Go's range loop syntax (Go 1.22+ range-over-func feature). The iteration can be stopped early by the consumer returning false from
the yield function.
Type Parameters:
T - the type of values to enumerate (no constraints)
Notes:
- Thread safety depends on the implementation
- Designed to work with Go 1.22+ range-over-func feature
func EmptyAny ¶
func EmptyAny[T any]() EnumeratorAny[T]
EmptyAny returns an empty enumerator of type T that yields no values.
The returned EnumeratorAny[T] will immediately terminate any range loop without executing the loop body, as there are no values to enumerate.
Returns:
An empty EnumeratorAny[T] that can be used in range loops (Go 1.22+).
Notes:
- Can represent "no results" in a type-safe way
- Works with any type T (no constraints)
func FromChannelAny ¶
func FromChannelAny[T any](ch <-chan T) EnumeratorAny[T]
FromChannelAny creates an EnumeratorAny[T] that yields values received from a channel. The enumeration continues until the channel is closed or the consumer stops iteration.
The enumerator will:
- Yield each value received from the channel in order
- Terminate when the channel is closed
- Support early termination when the consumer returns false
Parameters:
ch - the source channel to enumerate (read-only)
Returns:
An EnumeratorAny[T] that iterates over channel values
Notes:
- The enumerator will block waiting for new values when channel is empty
- If the channel is never closed, iteration may hang indefinitely
- Safe for nil channels (will act like closed channels, producing no values)
- Channel receive operations occur during enumeration (not beforehand)
- The channel should only be read through the enumerator
func FromSliceAny ¶
func FromSliceAny[T any](items []T) EnumeratorAny[T]
FromSliceAny creates an EnumeratorAny[T] that yields all elements from the input slice in order.
The enumerator will produce exactly len(items) values, one for each element in the original slice, preserving their original order. The iteration can be stopped early by the consumer.
Parameters:
items - slice of elements to enumerate (no type constraints)
Returns:
An EnumeratorAny[T] that iterates over the slice elements
Notes:
- The slice is captured by reference (modifications will affect iteration)
- For empty slices, produces no values
- Safe for nil slices (treated as empty)
- Preserves the original element order
func RangeAny ¶
func RangeAny(start, count int) EnumeratorAny[int]
RangeAny generates a sequence of consecutive integers starting at 'start', producing exactly 'count' values in ascending order (with step +1).
Parameters:
start - initial value of the sequence (inclusive) count - number of values to generate (must be non-negative)
Returns:
An EnumeratorAny[int] that can be used in range loops.
Notes:
- For count = 0, produces an empty sequence (no iterations)
- For count < 0, behavior is undefined (should be avoided)
func RepeatAny ¶
func RepeatAny[T any](item T, count int) EnumeratorAny[T]
RepeatAny generates a sequence containing the same item repeated 'count' times.
Parameters:
item - value to repeat (any type) count - number of repetitions (must be non-negative)
Returns:
An EnumeratorAny[T] that can be used in range loops.
Notes:
- For count = 0, produces an empty sequence (no iterations)
- For count < 0, behavior is undefined (should be avoided)
- Works with any type T (comparable and non-comparable types)
func (EnumeratorAny[T]) All ¶
func (q EnumeratorAny[T]) All(predicate func(T) bool) bool
All determines whether all elements in the enumeration satisfy a predicate. Returns true if every element matches the predicate, or if the enumeration is empty.
The method will:
- Apply the predicate to each element in the enumeration
- Return false immediately when the first non-matching element is found
- Return true if all elements match or if there are no elements
- Short-circuit evaluation (stops at first false result)
Parameters:
predicate - a function that takes an element and returns true/false
Returns:
true if all elements satisfy the predicate or enumeration is empty false if at least one element does not satisfy the predicate
Notes:
- For empty enumerations, returns true (vacuous truth)
- For nil enumerators, returns true (consistent with empty behavior)
- Uses short-circuit evaluation for performance
- The predicate function should be pure (no side effects)
- Stops enumeration as soon as a non-matching element is found
func (EnumeratorAny[T]) Any ¶
func (q EnumeratorAny[T]) Any() bool
Any determines whether an enumeration contains any elements. This operation is useful for checking if a sequence is non-empty.
The any operation will:
- Return true if the enumeration contains at least one element
- Return false if the enumeration is empty or nil
- Stop enumeration immediately after finding the first element
- Handle nil enumerators gracefully
Returns:
true if the enumeration contains any elements, false otherwise
Notes:
- If the enumerator is nil, returns false
- If the enumeration is empty, returns false
- Lazy evaluation stops immediately after finding the first element
- This is a terminal operation that materializes the enumeration
- Very efficient - O(1) time complexity for non-empty enumerations
- No elements are buffered - memory efficient
func (EnumeratorAny[T]) AverageFloat ¶ added in v1.25.3
func (e EnumeratorAny[T]) AverageFloat(keySelector func(T) float32) (float64, bool)
AverageFloat returns the arithmetic mean of float32 values extracted from elements of the enumeration using a key selector function. This operation is useful for calculating the average numeric value derived from complex elements.
The AverageFloat operation will:
- Apply the keySelector function to each element to extract a float32 value
- Calculate the sum of all extracted float32 values
- Divide the sum by the count of elements to compute the arithmetic mean
- Return the average as float64 and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts a float32 key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The arithmetic mean of extracted float32 values as float64 and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to calculate the sum and count. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it must process the entire enumeration, which may trigger upstream operations.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Returns float64 for higher precision in result
- For empty enumerations, no division by zero occurs (returns false)
- To calculate average of other numeric types, use AverageInt, AverageInt64, or AverageFloat64
func (EnumeratorAny[T]) AverageFloat64 ¶ added in v1.25.3
func (e EnumeratorAny[T]) AverageFloat64(keySelector func(T) float64) (float64, bool)
AverageFloat64 returns the arithmetic mean of float64 values extracted from elements of the enumeration using a key selector function. This operation is useful for calculating the average numeric value derived from complex elements.
The AverageFloat64 operation will:
- Apply the keySelector function to each element to extract a float64 value
- Calculate the sum of all extracted float64 values
- Divide the sum by the count of elements to compute the arithmetic mean
- Return the average as float64 and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts a float64 key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The arithmetic mean of extracted float64 values as float64 and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to calculate the sum and count. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it must process the entire enumeration, which may trigger upstream operations.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- For empty enumerations, no division by zero occurs (returns false)
- To calculate average of other numeric types, use AverageInt, AverageInt64, or AverageFloat
func (EnumeratorAny[T]) AverageInt ¶ added in v1.25.3
func (e EnumeratorAny[T]) AverageInt(keySelector func(T) int) (float64, bool)
AverageInt returns the arithmetic mean of integer values extracted from elements of the enumeration using a key selector function. This operation is useful for calculating the average numeric value derived from complex elements.
The AverageInt operation will:
- Apply the keySelector function to each element to extract an int value
- Calculate the sum of all extracted integer values
- Divide the sum by the count of elements to compute the arithmetic mean
- Return the average as float64 and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts an int key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The arithmetic mean of extracted integer values as float64 and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to calculate the sum and count. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it must process the entire enumeration, which may trigger upstream operations.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Returns float64 to accommodate fractional results from integer division
- Uses int64 internally to prevent integer overflow during summation
- For empty enumerations, no division by zero occurs (returns false)
- To calculate average of other numeric types, use AverageInt64, AverageFloat, or AverageFloat64
func (EnumeratorAny[T]) AverageInt64 ¶ added in v1.25.3
func (e EnumeratorAny[T]) AverageInt64(keySelector func(T) int64) (float64, bool)
AverageInt64 returns the arithmetic mean of int64 values extracted from elements of the enumeration using a key selector function. This operation is useful for calculating the average numeric value derived from complex elements.
The AverageInt64 operation will:
- Apply the keySelector function to each element to extract an int64 value
- Calculate the sum of all extracted int64 values
- Divide the sum by the count of elements to compute the arithmetic mean
- Return the average as float64 and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts an int64 key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The arithmetic mean of extracted int64 values as float64 and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to calculate the sum and count. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it must process the entire enumeration, which may trigger upstream operations.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Returns float64 to accommodate fractional results from integer division
- Uses float64 internally to handle large int64 values and prevent overflow
- For empty enumerations, no division by zero occurs (returns false)
- To calculate average of other numeric types, use AverageInt, AverageFloat, or AverageFloat64
func (EnumeratorAny[T]) Concat ¶
func (q EnumeratorAny[T]) Concat(second EnumeratorAny[T]) EnumeratorAny[T]
Concat combines two enumerations into a single enumeration. The resulting enumeration yields all elements from the first enumeration, followed by all elements from the second enumeration.
The concatenation will:
- Yield all elements from the first enumeration in order
- Then yield all elements from the second enumeration in order
- Handle nil enumerators gracefully (treated as empty)
- Support early termination when consumer returns false
Parameters:
second - the enumerator to concatenate after the current one
Returns:
A new EnumeratorAny[T] that yields elements from both enumerations in sequence
Notes:
- Nil enumerators are treated as empty (no elements yielded)
- Both enumerations are consumed in order during iteration
- If the first enumeration is infinite, second will never be reached
- Lazy evaluation - elements are produced on-demand during iteration
- No elements are buffered - memory efficient
- Safe for use with any combination of nil and non-nil enumerators
func (EnumeratorAny[T]) Contains ¶ added in v1.25.6
func (e EnumeratorAny[T]) Contains(value T, comparer comparer.EqualityComparer[T]) bool
Contains determines whether a sequence contains a specified element using the provided equality comparer. This operation is useful when you need to check for the existence of a specific value in the sequence with custom equality logic.
The Contains operation will:
- Return true if the sequence contains an element equal to the specified value according to the comparer
- Return false if the sequence does not contain the specified value
- Return false if the enumerator is nil
- Return false if the comparer is nil
- Process elements sequentially until the element is found or sequence ends
- Use the provided equality comparer for element comparison
Parameters:
value - the value to locate in the sequence comparer - the EqualityComparer to use for element comparison
Returns:
true if the sequence contains an element equal to the specified value, false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the sequence until the element is found or sequence ends.
⚠️ Memory note: This operation does not buffer elements.
Notes:
- Uses the provided equality comparer for comparison
- If enumerator is nil, returns false
- If comparer is nil, returns false
- Processes elements sequentially - early termination when element is found
- No elements are buffered - memory efficient
- This is a terminal operation that materializes the enumeration
- Works with any type T (including non-comparable types) when used with appropriate comparer
func (EnumeratorAny[T]) Count ¶
func (q EnumeratorAny[T]) Count() int
Count returns the number of elements in an enumeration. This operation is useful for determining the size of a sequence.
The count operation will:
- Iterate through all elements in the enumeration
- Count each element encountered
- Return the total count
- Handle nil enumerators gracefully
Returns:
The number of elements in the enumeration (0 for empty or nil enumerations)
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to count all elements. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it must process the entire enumeration, which may trigger upstream operations.
Notes:
- If the enumerator is nil, returns 0
- If the enumeration is empty, returns 0
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(1) - constant space usage
- All elements are processed, even if consumer wants to stop early
func (EnumeratorAny[T]) DefaultIfEmpty ¶ added in v1.25.2
func (e EnumeratorAny[T]) DefaultIfEmpty(defaultValue T) EnumeratorAny[T]
DefaultIfEmpty returns an enumeration that contains the elements of the current enumeration, or a single default value if the current enumeration is empty.
The resulting enumeration will:
- Yield all elements from the current enumeration if it contains any elements
- Yield exactly one element (the specified default value) if the current enumeration is empty
- Handle nil enumerators gracefully (treated as empty, yields default value)
- Support early termination when consumer returns false
Parameters:
defaultValue - the value to yield if the current enumeration contains no elements
Returns:
A new EnumeratorAny[T] that yields either the original elements or the default value
Notes:
- Nil enumerators are treated as empty enumerations
- If the current enumeration yields at least one element, the default value is never yielded
- Even if enumeration is terminated early (yield returns false), default value is not added if at least one element was processed
- Lazy evaluation - elements are produced on-demand during iteration
- No elements are buffered - memory efficient
- Safe for use with nil enumerators
func (EnumeratorAny[T]) Distinct ¶ added in v1.25.9
func (q EnumeratorAny[T]) Distinct(comparer comparer.EqualityComparer[T]) EnumeratorAny[T]
Distinct returns an enumerator that yields only unique elements from the original enumeration using a custom equality comparer to determine uniqueness. Each element appears only once in the result, regardless of how many times it appears in the source.
The distinct operation will:
- Yield each unique element exactly once
- Preserve the order of first occurrence of each element
- Use the provided EqualityComparer to determine uniqueness
- Support early termination when consumer returns false
Returns:
An EnumeratorAny[T] that yields unique elements in order of first appearance
⚠️ Performance note: This operation buffers all unique elements encountered so far in memory. For enumerations with many unique elements, memory usage can become significant. The operation is not memory-bounded.
⚠️ Performance warning: This operation can be significantly slower than Distinct() for comparable types due to the overhead of EqualityComparer interface calls and hash-based collision resolution. Consider using Distinct() with comparable types when possible for better performance.
⚠️ Allocation warning: This operation performs multiple memory allocations during execution, especially for enumerations with many unique elements. Each unique element requires storage in internal hash buckets, leading to increased GC pressure.
Notes:
- Uses map[uint64][]T internally for tracking seen elements with collision chaining
- Memory usage grows with number of unique elements
- For nil enumerators, returns empty enumerator
- Lazy evaluation - elements processed during iteration
- Elements are compared using the provided EqualityComparer's Equals and GetHashCode methods
- The comparer must not be nil, or the operation will panic
- Time complexity: O(n) average case, O(n²) worst case with many hash collisions
- Space complexity: O(k) where k is the number of unique elements
func (EnumeratorAny[T]) ElementAt ¶ added in v1.25.5
func (e EnumeratorAny[T]) ElementAt(index int) (T, bool)
ElementAt returns the element at the specified index in the sequence. This operation is useful when you need to access an element at a specific position without iterating through the entire sequence.
The ElementAt operation will:
- Return the element at the specified zero-based index and true if found
- Return the zero value of T and false if index is negative
- Return the zero value of T and false if index is beyond the sequence bounds
- Return the zero value of T and false if the enumerator is nil
- Process elements sequentially until the specified index is reached
Parameters:
index - the zero-based index of the element to retrieve
Returns:
The element at the specified index and true if found, zero value of T and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the sequence until the specified index is reached. Time complexity: O(n) where n is index + 1.
⚠️ Memory note: This operation does not buffer elements, only tracks current position.
Notes:
- Index must be non-negative (negative indices return zero value and false)
- If index is beyond sequence bounds, returns zero value and false
- If enumerator is nil, returns zero value and false
- Processes elements sequentially - early termination when index is found
- No elements are buffered - memory efficient
- This is a terminal operation that materializes the enumeration
- Works with any type T (including non-comparable types)
func (EnumeratorAny[T]) Except ¶ added in v1.25.11
func (e EnumeratorAny[T]) Except(second EnumeratorAny[T], comparer comparer.EqualityComparer[T]) EnumeratorAny[T]
Except returns an enumerator that yields elements from the first enumeration that are not present in the second enumeration using the provided equality comparer. This is equivalent to set difference operation (first - second).
The except operation will:
- Yield elements that exist in the first enumeration but not in the second
- Remove duplicates from the result (each element appears only once)
- Preserve the order of first occurrence from the first enumeration
- Handle nil enumerators gracefully
- Use the provided equality comparer for element comparison
Parameters:
second - the enumerator containing elements to exclude comparer - an EqualityComparer that defines when two elements are considered equal
Returns:
An Enumerator[T] that yields elements from first enumeration not in second
⚠️ Performance note: This operation completely buffers the `second` enumerator into memory (creates a hash set for fast lookup). For large second enumerations, this may consume significant memory. The memory usage is proportional to the number of unique elements in the second enumerator.
⚠️ Memory note: This operation buffers elements from both enumerations for duplicate detection and exclusion checking. Memory usage scales with the number of unique elements in both enumerations.
Notes:
- Uses the provided equality comparer's Equals and GetHashCode methods
- Result contains only unique elements (duplicates removed)
- For nil first enumerator, returns empty enumeration
- For nil second enumerator, returns distinct elements from first
- For nil comparer, returns empty enumeration
- Lazy evaluation - elements processed during iteration
- Memory usage depends on size of second enumeration and unique elements in first
- Supports any type T when used with appropriate comparer
- Works with non-comparable types through custom equality logic
- Hash codes are used for efficient O(1) average case lookup performance
- Hash collisions are resolved using exact equality comparison
func (EnumeratorAny[T]) FirstOrDefault ¶
func (q EnumeratorAny[T]) FirstOrDefault(defaultValue T) T
FirstOrDefault returns the first element of an enumeration, or a default value if the enumeration is empty or nil.
The first or default operation will:
- Return the first element from the enumeration if it exists
- Return the provided default value if the enumeration is empty or nil
- Stop enumeration immediately after finding the first element
- Handle nil enumerators gracefully
Parameters:
defaultValue - the value to return if the enumeration is empty or nil
Returns:
The first element of the enumeration, or the default value if enumeration is empty
Notes:
- If the enumerator is nil, returns the defaultValue
- If the enumeration is empty, returns the defaultValue
- Lazy evaluation stops immediately after finding the first element
- This is a terminal operation that materializes the enumeration
- Very efficient - O(1) time complexity for non-empty enumerations
- No elements are buffered - memory efficient
- Unlike FirstOrNil(), this method returns the value directly, not a pointer
- Safe for all types including those with zero values like 0, "", false, etc.
- When using zero value as default, consider using FirstOrNil() for distinction
func (EnumeratorAny[T]) FirstOrNil ¶
func (q EnumeratorAny[T]) FirstOrNil() *T
FirstOrNil returns a pointer to the first element of an enumeration. This operation is useful for getting the first element when it exists, with the ability to distinguish between "no elements" and "zero value" cases.
The first operation will:
- Return a pointer to the first element if the enumeration contains elements
- Return nil if the enumeration is empty or nil
- Stop enumeration immediately after finding the first element
- Handle nil enumerators gracefully
Returns:
A pointer to the first element, or nil if enumeration is empty or nil
Notes:
- If the enumerator is nil, returns nil
- If the enumeration is empty, returns nil
- Lazy evaluation stops immediately after finding the first element
- This is a terminal operation that materializes the enumeration
- Very efficient - O(1) time complexity for non-empty enumerations
- No elements are buffered - memory efficient
- Returns pointer to allow distinction between "no elements" (nil) and "zero value" element
- Safe for all types including those with zero values like 0, "", false, etc.
func (EnumeratorAny[T]) ForEach ¶
func (q EnumeratorAny[T]) ForEach(action func(T))
ForEach executes the specified action for each element in the enumeration. This operation is useful for performing side effects like printing, logging, or modifying external state for each element.
The for each operation will:
- Execute the action function for each element in the enumeration
- Process all elements in the enumeration
- Handle nil enumerators gracefully
- Not return any value (void operation)
Parameters:
action - the action to execute for each element
⚠️ Performance note: This operation must iterate through the entire enumeration, which may be expensive for large enumerations.
⚠️ Side effects warning: The action function may have side effects. Use with caution in functional programming contexts.
Notes:
- If the enumerator is nil, no action is executed
- This is a terminal operation that materializes the enumeration
- All elements are processed regardless of action behavior
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(1) - constant space usage
- The enumeration stops only when exhausted or if upstream operations stop it
- Action function should handle all possible values including zero values
func (EnumeratorAny[T]) LastOrDefault ¶
func (q EnumeratorAny[T]) LastOrDefault(defaultValue T) T
LastOrDefault returns the last element of an enumeration, or a default value if the enumeration is empty or nil.
The last or default operation will:
- Iterate through all elements in the enumeration
- Keep track of the most recent element encountered
- Return the last element if enumeration contains elements
- Return the provided default value if the enumeration is empty or nil
- Handle nil enumerators gracefully
Parameters:
defaultValue - the value to return if the enumeration is empty or nil
Returns:
The last element of the enumeration, or the default value if enumeration is empty
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the last element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it must process the entire enumeration, which may trigger upstream operations.
Notes:
- If the enumerator is nil, returns the defaultValue
- If the enumeration is empty, returns the defaultValue
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(1) - constant space usage
- Unlike LastOrNil(), this method returns the value directly, not a pointer
- Safe for all types including those with zero values like 0, "", false, etc.
- When using zero value as default, consider using LastOrNil() for distinction
func (EnumeratorAny[T]) LastOrNil ¶
func (q EnumeratorAny[T]) LastOrNil() *T
LastOrNil returns a pointer to the last element of an enumeration, or nil if the enumeration is empty or nil.
The last or nil operation will:
- Iterate through all elements in the enumeration
- Keep track of the most recent element encountered
- Return a pointer to the last element if enumeration contains elements
- Return nil if the enumeration is empty or nil
- Handle nil enumerators gracefully
Returns:
A pointer to the last element, or nil if enumeration is empty or nil
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the last element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it must process the entire enumeration, which may trigger upstream operations.
Notes:
- If the enumerator is nil, returns nil
- If the enumeration is empty, returns nil
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(1) - constant space usage
- Returns pointer to allow distinction between "no elements" (nil) and "zero value" element
- Safe for all types including those with zero values like 0, "", false, etc.
func (EnumeratorAny[T]) LongCount ¶
func (q EnumeratorAny[T]) LongCount() int64
LongCount returns the number of elements in an enumeration as an int64. This operation is useful for determining the size of large sequences where the count might exceed the range of int.
The long count operation will:
- Iterate through all elements in the enumeration
- Count each element encountered using int64 to prevent overflow
- Return the total count as int64
- Handle nil enumerators gracefully
Returns:
The number of elements in the enumeration as int64 (0 for empty or nil enumerations)
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to count all elements. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it must process the entire enumeration, which may trigger upstream operations.
Notes:
- If the enumerator is nil, returns 0
- If the enumeration is empty, returns 0
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(1) - constant space usage
- In Go, int is platform-dependent (32-bit on 32-bit systems, 64-bit on 64-bit systems)
- Use LongCount when you expect very large collections that might overflow int
func (EnumeratorAny[T]) MaxBool ¶ added in v1.25.2
func (e EnumeratorAny[T]) MaxBool(keySelector func(T) bool) (bool, bool)
MaxBool returns the largest boolean value extracted from elements of the enumeration using a key selector function and natural boolean ordering (false < true). This operation is useful for finding the maximum boolean key derived from complex elements.
The MaxBool operation will:
- Apply the keySelector function to each element to extract a bool value
- Compare extracted keys using natural boolean ordering (true > false)
- Return the largest bool key and true if the enumeration is non-empty
- Return false and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when true is found (since true is the maximum value)
Parameters:
keySelector - a function that extracts a bool key from each element of type T.
Must be non-nil; if nil, the operation returns (false, false).
Returns:
The maximum bool key value extracted from elements and true if found, false and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the maximum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (false, false)
- If keySelector is nil, returns (false, false)
- If the enumeration is empty, returns (false, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same maximal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when true is found (since true > false)
- For large enumerations without true values, all elements may be processed
- To use custom ordering, use MaxBoolBy with a custom comparer
- To get the original element associated with the maximum key, use MaxBy instead
func (EnumeratorAny[T]) MaxBy ¶ added in v1.25.2
func (e EnumeratorAny[T]) MaxBy(cmp comparer.ComparerFunc[T]) (T, bool)
MaxBy returns the largest element in the enumeration according to a custom comparison function. This operation is useful for finding the maximum element based on custom ordering criteria.
The MaxBy operation will:
- Return the largest element and true if the enumeration is non-empty
- Return the zero value of T and false if the enumeration is empty or nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators gracefully
- Use the provided comparer function to determine element ordering
Parameters:
cmp - a ComparerFunc that defines the ordering of elements by returning:
-1 if x < y, 0 if x == y, +1 if x > y
Returns:
The maximum element according to the comparer function and true if found, zero value of T and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the maximum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns zero value and false
- If the enumeration is empty, returns zero value and false
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The comparer function is called for each element pair during processing
- If multiple elements are equally maximal, the first one encountered is returned
- This is a terminal operation that materializes the enumeration
- The comparer function must be consistent and deterministic for correct results
- For large enumerations, consider the performance cost of the comparison operations
- The comparer should satisfy mathematical comparison properties (consistency, antisymmetry, transitivity)
- To find the minimum element, use MinBy instead
- Thread safety depends on the underlying enumerator implementation
func (EnumeratorAny[T]) MaxByte ¶ added in v1.25.2
func (e EnumeratorAny[T]) MaxByte(keySelector func(T) byte) (byte, bool)
MaxByte returns the largest byte value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the maximum numeric byte key derived from complex elements.
The MaxByte operation will:
- Apply the keySelector function to each element to extract a byte value
- Compare extracted keys using natural numeric ordering (0 to 255)
- Return the largest byte key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when 255 is found (since 255 is the maximum value)
Parameters:
keySelector - a function that extracts a byte key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The maximum byte key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that iterates through the enumeration to find the maximum element. Performance is optimized with early termination when 255 is found, but worst-case scenario processes all elements.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same maximal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when 255 is found (since 255 is the maximum byte value)
- For large enumerations without 255 values, all elements may be processed
- To get the original element associated with the maximum key, use MaxBy instead
func (EnumeratorAny[T]) MaxFloat ¶ added in v1.25.2
func (e EnumeratorAny[T]) MaxFloat(keySelector func(T) float32) (float32, bool)
MaxFloat returns the largest float32 value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the maximum numeric float32 key derived from complex elements.
The MaxFloat operation will:
- Apply the keySelector function to each element to extract a float32 value
- Compare extracted keys using natural numeric ordering
- Return the largest float32 key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when +Inf is found (since +Inf is the maximum value)
Parameters:
keySelector - a function that extracts a float32 key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The maximum float32 key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the maximum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same maximal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when +Inf is found (since +Inf is the maximum float32 value)
- For large enumerations without +Inf values, all elements may be processed
- To get the original element associated with the maximum key, use MaxBy instead
func (EnumeratorAny[T]) MaxFloat64 ¶ added in v1.25.2
func (e EnumeratorAny[T]) MaxFloat64(keySelector func(T) float64) (float64, bool)
MaxFloat64 returns the largest float64 value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the maximum numeric float64 key derived from complex elements.
The MaxFloat64 operation will:
- Apply the keySelector function to each element to extract a float64 value
- Compare extracted keys using natural numeric ordering
- Return the largest float64 key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when +Inf is found (since +Inf is the maximum value)
Parameters:
keySelector - a function that extracts a float64 key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The maximum float64 key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the maximum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same maximal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when +Inf is found (since +Inf is the maximum float64 value)
- For large enumerations without +Inf values, all elements may be processed
- To get the original element associated with the maximum key, use MaxBy instead
func (EnumeratorAny[T]) MaxInt ¶ added in v1.25.2
func (e EnumeratorAny[T]) MaxInt(keySelector func(T) int) (int, bool)
MaxInt returns the largest integer value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the maximum numeric key (such as ID, age, price, etc.) derived from complex elements in the sequence.
The MaxInt operation will:
- Apply the keySelector function to each element to extract an int value
- Compare extracted keys using natural numeric ordering (descending)
- Return the largest int key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts an int key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The maximum int key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the maximum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- If multiple elements yield the same maximal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- For large enumerations, consider the performance cost of key extraction
- To get the original element associated with the maximum key, use MaxBy instead
func (EnumeratorAny[T]) MaxInt64 ¶ added in v1.25.2
func (e EnumeratorAny[T]) MaxInt64(keySelector func(T) int64) (int64, bool)
MaxInt64 returns the largest int64 value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the maximum numeric key (such as ID, timestamp, size, etc.) derived from complex elements in the sequence.
The MaxInt64 operation will:
- Apply the keySelector function to each element to extract an int64 value
- Compare extracted keys using natural numeric ordering (descending)
- Return the largest int64 key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts an int64 key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The maximum int64 key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the maximum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- If multiple elements yield the same maximal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- For large enumerations, consider the performance cost of key extraction
- To get the original element associated with the maximum key, use MaxBy instead
func (EnumeratorAny[T]) MaxRune ¶ added in v1.25.2
func (e EnumeratorAny[T]) MaxRune(keySelector func(T) rune) (rune, bool)
MaxRune returns the largest rune value extracted from elements of the enumeration using a key selector function and natural Unicode code point ordering. This operation is useful for finding the maximum Unicode character key derived from complex elements.
The MaxRune operation will:
- Apply the keySelector function to each element to extract a rune value
- Compare extracted keys using natural Unicode code point ordering
- Return the largest rune key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when maximum Unicode code point is found
Parameters:
keySelector - a function that extracts a rune key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The maximum rune key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the maximum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same maximal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when maximum Unicode code point is found
- For large enumerations without maximum values, all elements may be processed
- To get the original element associated with the maximum key, use MaxBy instead
func (EnumeratorAny[T]) MaxString ¶ added in v1.25.2
func (e EnumeratorAny[T]) MaxString(keySelector func(T) string) (string, bool)
MaxString returns the lexicographically largest string value extracted from elements of the enumeration using a key selector function and natural string ordering. This operation is useful for finding the maximum string key derived from complex elements.
The MaxString operation will:
- Apply the keySelector function to each element to extract a string value
- Compare extracted keys using natural lexicographic ordering
- Return the largest string key and true if the enumeration is non-empty
- Return empty string ("") and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts a string key from each element of type T.
Must be non-nil; if nil, the operation returns ("", false).
Returns:
The maximum string key value extracted from elements and true if found,
empty string ("") and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the maximum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns ("", false)
- If keySelector is nil, returns ("", false)
- If the enumeration is empty, returns ("", false)
- Processes elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- If multiple elements yield the same maximal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- For large enumerations, all elements may be processed (no early termination optimization)
- To get the original element associated with the maximum key, use MaxBy instead
func (EnumeratorAny[T]) MaxTime ¶ added in v1.25.2
MaxTime returns the latest time.Time value extracted from elements of the enumeration using a key selector function and natural time ordering. This operation is useful for finding the maximum timestamp key derived from complex elements.
The MaxTime operation will:
- Apply the keySelector function to each element to extract a time.Time value
- Compare extracted keys using natural time ordering
- Return the latest time.Time key and true if the enumeration is non-empty
- Return zero time (time.Time{}) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts a time.Time key from each element of type T.
Must be non-nil; if nil, the operation returns (time.Time{}, false).
Returns:
The maximum time.Time key value extracted from elements and true if found,
zero time (time.Time{}) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the maximum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (time.Time{}, false)
- If keySelector is nil, returns (time.Time{}, false)
- If the enumeration is empty, returns (time.Time{}, false)
- Processes elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- If multiple elements yield the same maximal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- For large enumerations, all elements may be processed (no early termination optimization)
- To get the original element associated with the maximum key, use MaxBy instead
func (EnumeratorAny[T]) MinBool ¶ added in v1.25.2
func (e EnumeratorAny[T]) MinBool(keySelector func(T) bool) (bool, bool)
MinBool returns the smallest boolean value extracted from elements of the enumeration using a key selector function and natural boolean ordering (false < true). This operation is useful for finding the minimum boolean key derived from complex elements.
Same as Enumerator[T].MinBool, but operates on EnumeratorAny[T].
Parameters:
keySelector - a function that extracts a bool key from each element of type T.
Must be non-nil; if nil, the operation returns (false, false).
Returns:
The minimum bool key value extracted from elements and true if found, false and false otherwise
⚠️ Performance note: This is a terminal operation that iterates through the enumeration to find the minimum element. Performance is optimized with early termination when false is found, but worst-case scenario processes all elements.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (false, false)
- If keySelector is nil, returns (false, false)
- If the enumeration is empty, returns (false, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same minimal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when false is found (since false < true)
- For large enumerations without false values, all elements may be processed
- To get the original element associated with the minimum key, use MinBy instead
func (EnumeratorAny[T]) MinBy ¶ added in v1.25.2
func (e EnumeratorAny[T]) MinBy(cmp comparer.ComparerFunc[T]) (T, bool)
MinBy returns the smallest element in the enumeration according to a custom comparison function. This operation is useful for finding the minimum element based on custom ordering criteria.
The minby operation will:
- Return the smallest element and true if the enumeration is non-empty
- Return the zero value of T and false if the enumeration is empty or nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators gracefully
- Use the provided comparer function to determine element ordering
Parameters:
cmp - a ComparerFunc that defines the ordering of elements by returning:
-1 if x < y, 0 if x == y, +1 if x > y
Returns:
The minimum element according to the comparer function and true if found, zero value of T and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the minimum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns zero value and false
- If the enumeration is empty, returns zero value and false
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The comparer function is called for each element pair during processing
- If multiple elements are equally minimal, the first one encountered is returned
- This is a terminal operation that materializes the enumeration
- The comparer function must be consistent and deterministic for correct results
- For large enumerations, consider the performance cost of the comparison operations
- The comparer should satisfy mathematical comparison properties (consistency, antisymmetry, transitivity)
func (EnumeratorAny[T]) MinByte ¶ added in v1.25.2
func (e EnumeratorAny[T]) MinByte(keySelector func(T) byte) (byte, bool)
MinByte returns the smallest byte value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the minimum numeric byte key derived from complex elements.
The MinByte operation will:
- Apply the keySelector function to each element to extract a byte value
- Compare extracted keys using natural numeric ordering (0 to 255)
- Return the smallest byte key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when 0 is found (since 0 is the minimum value)
Parameters:
keySelector - a function that extracts a byte key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The minimum byte key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that iterates through the enumeration to find the minimum element. Performance is optimized with early termination when 0 is found, but worst-case scenario processes all elements.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same minimal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when 0 is found (since 0 is the minimum byte value)
- For large enumerations without 0 values, all elements may be processed
- To use custom ordering, use MinByteBy with a custom comparer
- To get the original element associated with the minimum key, use MinBy instead
func (EnumeratorAny[T]) MinFloat ¶ added in v1.25.2
func (e EnumeratorAny[T]) MinFloat(keySelector func(T) float32) (float32, bool)
MinFloat returns the smallest float32 value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the minimum numeric float32 key derived from complex elements.
The MinFloat operation will:
- Apply the keySelector function to each element to extract a float32 value
- Compare extracted keys using natural numeric ordering
- Return the smallest float32 key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when -Inf is found (since -Inf is the minimum value)
Parameters:
keySelector - a function that extracts a float32 key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The minimum float32 key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the minimum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same minimal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when -Inf is found (since -Inf is the minimum float32 value)
- For large enumerations without -Inf values, all elements may be processed
- To get the original element associated with the minimum key, use MinBy instead
func (EnumeratorAny[T]) MinFloat64 ¶ added in v1.25.2
func (e EnumeratorAny[T]) MinFloat64(keySelector func(T) float64) (float64, bool)
MinFloat64 returns the smallest float64 value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the minimum numeric float64 key derived from complex elements.
The MinFloat64 operation will:
- Apply the keySelector function to each element to extract a float64 value
- Compare extracted keys using natural numeric ordering
- Return the smallest float64 key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when -Inf is found (since -Inf is the minimum value)
Parameters:
keySelector - a function that extracts a float64 key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The minimum float64 key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the minimum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same minimal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when -Inf is found (since -Inf is the minimum float64 value)
- For large enumerations without -Inf values, all elements may be processed
- To get the original element associated with the minimum key, use MinBy instead
func (EnumeratorAny[T]) MinInt ¶ added in v1.25.2
func (e EnumeratorAny[T]) MinInt(keySelector func(T) int) (int, bool)
MinInt returns the smallest integer value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the minimum numeric key (such as ID, age, price, etc.) derived from complex elements in the sequence.
The MinInt operation will:
- Apply the keySelector function to each element to extract an int value
- Compare extracted keys using natural numeric ordering (ascending)
- Return the smallest int key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts an int key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The minimum int key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the minimum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- If multiple elements yield the same minimal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- For large enumerations, consider the performance cost of key extraction
- To get the original element associated with the minimum key, use MinBy instead
func (EnumeratorAny[T]) MinInt64 ¶ added in v1.25.2
func (e EnumeratorAny[T]) MinInt64(keySelector func(T) int64) (int64, bool)
MinInt64 returns the smallest int64 value extracted from elements of the enumeration using a key selector function and natural numeric ordering. This operation is useful for finding the minimum numeric key (such as ID, timestamp, size, etc.) derived from complex elements in the sequence.
The MinInt64 operation will:
- Apply the keySelector function to each element to extract an int64 value
- Compare extracted keys using natural numeric ordering (ascending)
- Return the smallest int64 key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
Parameters:
keySelector - a function that extracts an int64 key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The minimum int64 key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to find the minimum element. For large enumerations, this may be expensive.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes all elements in the enumeration - O(n) time complexity
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element
- If multiple elements yield the same minimal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- For large enumerations, consider the performance cost of key extraction
- To get the original element associated with the minimum key, use MinBy instead
func (EnumeratorAny[T]) MinRune ¶ added in v1.25.2
func (e EnumeratorAny[T]) MinRune(keySelector func(T) rune) (rune, bool)
MinRune returns the smallest rune value extracted from elements of the enumeration using a key selector function and natural Unicode code point ordering. This operation is useful for finding the minimum Unicode character key derived from complex elements.
The MinRune operation will:
- Apply the keySelector function to each element to extract a rune value
- Compare extracted keys using natural Unicode code point ordering
- Return the smallest rune key and true if the enumeration is non-empty
- Return zero value (0) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when 0 is found (since 0 is the minimum Unicode code point)
Parameters:
keySelector - a function that extracts a rune key from each element of type T.
Must be non-nil; if nil, the operation returns (0, false).
Returns:
The minimum rune key value extracted from elements and true if found, zero value (0) and false otherwise
⚠️ Performance note: This is a terminal operation that iterates through the enumeration to find the minimum element. Performance is optimized with early termination when 0 is found (since 0 is the minimum Unicode code point), but worst-case scenario processes all elements.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (0, false)
- If keySelector is nil, returns (0, false)
- If the enumeration is empty, returns (0, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same minimal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when 0 is found (since 0 is the minimum Unicode code point)
- For large enumerations without 0 values, all elements may be processed
- To get the original element associated with the minimum key, use MinBy instead
func (EnumeratorAny[T]) MinString ¶ added in v1.25.2
func (e EnumeratorAny[T]) MinString(keySelector func(T) string) (string, bool)
MinString returns the lexicographically smallest string value extracted from elements of the enumeration using a key selector function and natural string ordering. This operation is useful for finding the minimum string key derived from complex elements.
The MinString operation will:
- Apply the keySelector function to each element to extract a string value
- Compare extracted keys using natural lexicographic ordering
- Return the smallest string key and true if the enumeration is non-empty
- Return empty string ("") and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when empty string is found
Parameters:
keySelector - a function that extracts a string key from each element of type T.
Must be non-nil; if nil, the operation returns ("", false).
Returns:
The minimum string key value extracted from elements and true if found,
empty string ("") and false otherwise
⚠️ Performance note: This is a terminal operation that iterates through the enumeration to find the minimum element. Performance is optimized with early termination when empty string is found, but worst-case scenario processes all elements.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns ("", false)
- If keySelector is nil, returns ("", false)
- If the enumeration is empty, returns ("", false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same minimal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when empty string is found (since "" < any non-empty string)
- For large enumerations without empty strings, all elements may be processed
- To get the original element associated with the minimum key, use MinBy instead
func (EnumeratorAny[T]) MinTime ¶ added in v1.25.2
MinTime returns the earliest time.Time value extracted from elements of the enumeration using a key selector function and natural time ordering. This operation is useful for finding the minimum timestamp key derived from complex elements.
The MinTime operation will:
- Apply the keySelector function to each element to extract a time.Time value
- Compare extracted keys using natural time ordering
- Return the earliest time.Time key and true if the enumeration is non-empty
- Return zero time (time.Time{}) and false if the enumeration is empty, nil, or keySelector is nil
- Process elements sequentially until the end of the enumeration
- Handle nil enumerators and nil functions gracefully
- Optimize performance by early termination when zero time is found
Parameters:
keySelector - a function that extracts a time.Time key from each element of type T.
Must be non-nil; if nil, the operation returns (time.Time{}, false).
Returns:
The minimum time.Time key value extracted from elements and true if found,
zero time (time.Time{}) and false otherwise
⚠️ Performance note: This is a terminal operation that iterates through the enumeration to find the minimum element. Performance is optimized with early termination when zero time is found, but worst-case scenario processes all elements.
⚠️ Memory note: This operation does not buffer elements, but it may trigger upstream operations during enumeration.
Notes:
- If the enumerator is nil, returns (time.Time{}, false)
- If keySelector is nil, returns (time.Time{}, false)
- If the enumeration is empty, returns (time.Time{}, false)
- Processes elements in the enumeration - O(n) worst-case time complexity, but may terminate early
- No elements are buffered - memory efficient
- The keySelector function is called exactly once per element until termination
- If multiple elements yield the same minimal key, the first one encountered is used
- This is a terminal operation that materializes the enumeration
- The keySelector function should be deterministic for consistent results
- Performance is optimized: terminates early when zero time is found (since time.Time{} is the earliest possible time)
- For large enumerations without zero times, all elements may be processed
- To get the original element associated with the minimum key, use MinBy instead
func (EnumeratorAny[T]) OrderBy ¶ added in v1.25.7
func (e EnumeratorAny[T]) OrderBy(comparer comparer.ComparerFunc[T]) OrderEnumeratorAny[T]
OrderBy sorts the elements of a sequence in ascending order according to a comparer function. This method is the primary sorting operation for any type T, including non-comparable types.
The OrderBy operation:
- Accumulates sorting rules without immediate execution (lazy evaluation)
- Returns an OrderEnumeratorAny that supports fluent chaining with ThenBy operations
- Uses the provided comparer function to determine element ordering
- Maintains stable sorting (equal elements preserve relative order)
- Works with any type T, including non-comparable types
Parameters:
comparer - a ComparerFunc that defines the sort order by comparing two elements of type T
The function should return:
< 0 if first element is less than second
= 0 if elements are equal
> 0 if first element is greater than second
Returns:
An OrderEnumeratorAny[T] that contains the sorted elements and supports further sorting operations
⚠️ Performance note: This is a deferred execution operation that accumulates sorting rules. Actual sorting computation occurs during first enumeration. Time complexity: O(1) for rule accumulation, O(n log n) for actual sorting during enumeration.
Notes:
- This is a lazy operation - no sorting occurs until enumeration begins
- Works with any type T, including complex structs with non-comparable fields
- Custom comparer functions must handle all possible input values, including nil
- The comparer function must be deterministic and consistent
- For subsequent sorting levels, use ThenBy or ThenByDescending
- Thread-safe for rule accumulation, but enumeration should be single-threaded
func (EnumeratorAny[T]) OrderByDescending ¶ added in v1.25.7
func (e EnumeratorAny[T]) OrderByDescending(comparer comparer.ComparerFunc[T]) OrderEnumeratorAny[T]
OrderByDescending sorts the elements of a sequence in descending order according to a comparer function. This method is the primary sorting operation for any type T, including non-comparable types.
The OrderByDescending operation:
- Accumulates sorting rules without immediate execution (lazy evaluation)
- Returns an OrderEnumeratorAny that supports fluent chaining with ThenBy operations
- Uses the provided comparer function to determine element ordering (reversed)
- Maintains stable sorting (equal elements preserve relative order)
- Works with any type T, including non-comparable types
Parameters:
comparer - a ComparerFunc that defines the sort order by comparing two elements of type T
The function should return:
< 0 if first element is less than second
= 0 if elements are equal
> 0 if first element is greater than second
Note: The final order will be reversed (descending)
Returns:
An OrderEnumeratorAny[T] that contains the sorted elements and supports further sorting operations
⚠️ Performance note: This is a deferred execution operation that accumulates sorting rules. Actual sorting computation occurs during first enumeration. Time complexity: O(1) for rule accumulation, O(n log n) for actual sorting during enumeration.
Notes:
- This is a lazy operation - no sorting occurs until enumeration begins
- Works with any type T, including complex structs with non-comparable fields
- Custom comparer functions must handle all possible input values, including nil
- The comparer function must be deterministic and consistent
- For subsequent sorting levels, use ThenBy or ThenByDescending
- Thread-safe for rule accumulation, but enumeration should be single-threaded
func (EnumeratorAny[T]) SingleBy ¶ added in v1.25.4
func (e EnumeratorAny[T]) SingleBy(comparer comparer.EqualityComparer[T]) (T, error)
SingleBy returns the single element of a sequence that satisfies the provided equality comparer. This operation is useful when you expect exactly one element in the sequence and need custom equality logic.
The SingleBy operation will:
- Return the single element if the sequence contains exactly one distinct element according to the comparer
- Return an error if the sequence is empty ("sequence contains no elements")
- Return an error if the sequence contains more than one distinct element according to the comparer
- Process elements sequentially until completion or second distinct element found
- Handle nil enumerators gracefully
Parameters:
comparer - an EqualityComparer that defines when two elements are considered equal
Returns:
The single element of the sequence and nil error if successful, zero value of T and error otherwise
⚠️ Performance note: This is a terminal operation that must iterate through the sequence until completion or second distinct element found. For large sequences with multiple distinct elements, this may process more elements than necessary. Average time complexity: O(n) where n is the number of elements processed.
⚠️ Memory note: This operation buffers elements to perform equality comparison using hash-based lookup. Memory usage depends on the number of distinct elements encountered during processing. Worst case memory complexity: O(n) where n is the number of distinct elements.
Notes:
- If the enumerator is nil, returns zero value and error ("sequence contains no elements")
- If the enumeration is empty, returns zero value and error ("sequence contains no elements")
- If the enumeration contains more than one distinct element, returns zero value and error ("sequence contains more than one element")
- Uses the provided comparer's Equals and GetHashCode methods for efficient element comparison
- Elements are buffered in hash buckets during comparison for efficient duplicate detection
- This is a terminal operation that materializes the enumeration
- Works with any type T (including non-comparable types) when used with appropriate comparer
- The comparer functions must be consistent and deterministic
- For large enumerations, processing stops early when second distinct element is found
- This method should be used when you are certain the sequence contains exactly one distinct element
- Common use cases include lookup by custom equality logic, complex object comparison, or unique constraint validation
func (EnumeratorAny[T]) Skip ¶
func (q EnumeratorAny[T]) Skip(n int) EnumeratorAny[T]
Skip bypasses a specified number of elements in an enumeration and then yields the remaining elements. This operation is useful for pagination, skipping headers, or bypassing initial elements.
The skip operation will:
- Bypass the first n elements from the enumeration
- Yield all remaining elements in order
- Handle edge cases gracefully (n <= 0, n >= count)
- Support early termination when consumer returns false
Parameters:
n - the number of elements to skip (must be non-negative)
Returns:
An EnumeratorAny[T] that yields elements after skipping the first n elements
Notes:
- If n <= 0, returns the original enumerator unchanged
- If n >= total number of elements, returns an empty enumerator
- If the original enumerator is nil, returns an empty enumerator (not nil)
- Lazy evaluation - elements are processed and skipped during iteration
- No elements are buffered - memory efficient
- Negative values of n are treated as 0
- The enumeration is consumed sequentially, so skipped elements are still processed
func (EnumeratorAny[T]) SkipLast ¶
func (q EnumeratorAny[T]) SkipLast(n int) EnumeratorAny[T]
SkipLast bypasses a specified number of elements at the end of an enumeration and yields the remaining elements. This operation is useful for removing trailing elements like footers, summaries, or fixed-size endings from sequences.
The skip last operation will:
- Buffer elements to track which are the final n elements
- Yield elements only after confirming they are not among the last n
- Handle edge cases gracefully (n <= 0, n >= count)
- Support early termination when consumer returns false
Parameters:
n - the number of elements to skip from the end (must be non-negative)
Returns:
An EnumeratorAny[T] that yields elements except the last n elements
⚠️ Performance note: This operation buffers up to n elements in memory using a circular buffer for efficient memory usage. For large values of n, this may consume significant memory.
⚠️ Evaluation note: This operation is partially lazy - elements are processed as the enumeration proceeds, but the last n elements are buffered and never yielded. The enumeration must progress beyond n elements to yield earlier ones.
Notes:
- If n <= 0, returns the original enumerator unchanged
- If n >= total number of elements, returns an empty enumerator
- If the original enumerator is nil, returns an empty enumerator
- Elements are yielded in order of their appearance in the original enumeration
- Negative values of n are treated as 0
func (EnumeratorAny[T]) SkipWhile ¶
func (q EnumeratorAny[T]) SkipWhile(predicate func(T) bool) EnumeratorAny[T]
SkipWhile bypasses elements in an enumeration as long as a specified condition is true and then yields the remaining elements. This operation is useful for skipping elements until a certain condition is met.
The skip while operation will:
- Bypass elements from the beginning while the predicate returns true
- Once the predicate returns false for an element, yield that element and all subsequent elements
- Support early termination when consumer returns false
Parameters:
predicate - a function that determines whether to skip an element
Returns:
An EnumeratorAny[T] that yields elements after skipping initial elements that match the condition
Notes:
- If the predicate never returns false, returns an empty enumerator
- If the predicate immediately returns false for the first element, returns the original enumerator
- If the original enumerator is nil, returns an empty enumerator
- Lazy evaluation - elements are processed and evaluated during iteration
- No elements are buffered - memory efficient
- The enumeration stops skipping as soon as the first non-matching element is found
- Once skipping stops, all remaining elements are yielded (even if they would match the predicate)
func (EnumeratorAny[T]) SumFloat ¶
func (q EnumeratorAny[T]) SumFloat(selector func(T) float32) float32
SumFloat computes the sum of float32 values obtained by applying a selector function to each element in the enumeration. This operation is useful for calculating totals, aggregates, or numeric summaries with floating-point precision.
The sum float operation will:
- Apply the selector function to each element to extract a float32 value
- Sum all the extracted float32 values
- Return the total sum
- Handle nil enumerators gracefully
Parameters:
selector - a function that extracts a float32 value from each element
Returns:
The sum of all float32 values extracted from the elements
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to sum all values. For large enumerations, this may be expensive.
⚠️ Precision warning: Floating-point arithmetic may introduce small rounding errors. Consider using appropriate rounding for display.
Notes:
- If the enumerator is nil, returns 0
- If the enumeration is empty, returns 0
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(1) - constant space usage
- The enumeration stops only when exhausted or if upstream operations stop it
- Selector function should handle all possible input values safely
- For double precision, consider implementing or using SumFloat64
func (EnumeratorAny[T]) SumInt ¶
func (q EnumeratorAny[T]) SumInt(selector func(T) int) int
SumInt computes the sum of integers obtained by applying a selector function to each element in the enumeration. This operation is useful for calculating totals, aggregates, or numeric summaries.
The sum int operation will:
- Apply the selector function to each element to extract an integer value
- Sum all the extracted integer values
- Return the total sum
- Handle nil enumerators gracefully
Parameters:
selector - a function that extracts an integer value from each element
Returns:
The sum of all integer values extracted from the elements
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to sum all values. For large enumerations, this may be expensive.
⚠️ Overflow warning: Integer overflow may occur with very large sums. Consider using SumInt64 for larger ranges.
Notes:
- If the enumerator is nil, returns 0
- If the enumeration is empty, returns 0
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(1) - constant space usage
- The enumeration stops only when exhausted or if upstream operations stop it
- Selector function should handle all possible input values safely
func (EnumeratorAny[T]) Take ¶
func (q EnumeratorAny[T]) Take(n int) EnumeratorAny[T]
Take returns a specified number of contiguous elements from the start of an enumeration. This operation is useful for pagination, limiting results, or taking samples from sequences.
The take operation will:
- Yield the first n elements from the enumeration
- Stop enumeration once n elements have been yielded
- Handle edge cases gracefully (n <= 0, n >= count)
- Support early termination when consumer returns false
Parameters:
n - the number of elements to take (must be non-negative)
Returns:
An EnumeratorAny[T] that yields at most n elements from the start
Notes:
- If n <= 0, returns an empty enumerator
- If n >= total number of elements, returns all available elements
- If the original enumerator is nil, returns an empty enumerator
- Lazy evaluation - elements are processed and yielded during iteration
- No elements are buffered - memory efficient
- Negative values of n are treated as 0
- Early termination by the consumer stops further enumeration
- The enumeration stops as soon as n elements are yielded or the source is exhausted
func (EnumeratorAny[T]) TakeLast ¶
func (q EnumeratorAny[T]) TakeLast(n int) EnumeratorAny[T]
TakeLast returns a specified number of contiguous elements from the end of an enumeration. This operation is useful for getting the final elements, such as last N records, trailing averages, or end-of-sequence markers.
The take last operation will:
- Buffer elements to track the last n elements seen so far
- Yield the final n elements when enumeration completes
- Handle edge cases gracefully (n <= 0, n >= count)
- Support early termination when consumer returns false
Parameters:
n - the number of elements to take from the end (must be non-negative)
Returns:
An EnumeratorAny[T] that yields the last n elements
⚠️ Performance note: This operation buffers up to n elements in memory to track which elements should be yielded. For large values of n, this may consume significant memory. All elements must be processed before any are yielded.
⚠️ Evaluation note: This operation is not lazy in the traditional sense - the entire source enumeration must be consumed before yielding begins. Elements are yielded in order of their appearance in the original enumeration.
Notes:
- If n <= 0, returns an empty enumerator
- If n >= total number of elements, returns all available elements
- If the original enumerator is nil, returns an empty enumerator
- Negative values of n are treated as 0
- The enumeration stops as soon as the consumer returns false
func (EnumeratorAny[T]) TakeWhile ¶
func (q EnumeratorAny[T]) TakeWhile(predicate func(T) bool) EnumeratorAny[T]
TakeWhile returns elements from an enumeration as long as a specified condition is true. This operation is useful for taking elements until a certain condition is met, such as taking elements while they are valid or within a range.
The take while operation will:
- Yield elements from the start while the predicate returns true
- Stop enumeration as soon as the predicate returns false for an element
- Handle edge cases gracefully (nil enumerator, always false predicate)
- Support early termination when consumer returns false
Parameters:
predicate - a function that determines whether to take an element
Returns:
An EnumeratorAny[T] that yields elements while the condition is true
Notes:
- If the predicate immediately returns false for the first element, returns empty enumerator
- If the predicate never returns false, returns all elements from the enumeration
- If the original enumerator is nil, returns an empty enumerator
- Lazy evaluation - elements are processed and evaluated during iteration
- No elements are buffered - memory efficient
- The enumeration stops as soon as the predicate returns false or consumer returns false
- Once the predicate returns false for any element, no subsequent elements are evaluated
func (EnumeratorAny[T]) ToBatch ¶ added in v1.25.8
func (e EnumeratorAny[T]) ToBatch(batchSize int) [][]T
ToBatch groups elements from an enumeration into batches of specified size and returns them as a slice of slices. This operation is useful for processing large sequences in chunks, implementing pagination, or optimizing batch operations. This method supports any type T, including non-comparable types.
The to batch operation will:
- Group consecutive elements into slices of at most batchSize elements
- Return all batches as a slice when enumeration is complete
- Handle edge cases gracefully (batchSize <= 0, empty source)
- Materialize the entire enumeration (terminal operation)
Parameters:
batchSize - the maximum number of elements per batch (must be positive)
Returns:
A slice containing batches of elements, or empty slice if no batches
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to create all batches.
⚠️ Memory note: This operation buffers all elements in memory during processing.
Notes:
- If batchSize <= 0, returns empty slice
- If the original enumerator is nil, returns empty slice
- Last batch may contain fewer elements than batchSize
- Terminal operation - consumes entire enumeration
- Each batch is a separate slice - safe for modification
- No elements are lost - all elements from source are included in batches
- Supports complex types including structs with non-comparable fields
func (EnumeratorAny[T]) ToChannel ¶
func (q EnumeratorAny[T]) ToChannel(bufferSize int) <-chan T
ToChannel converts an enumeration to a channel that yields all elements. This operation is useful for converting lazy enumerations into channel-based processing pipelines or for interoperability with goroutines.
The to channel operation will:
- Create a new channel with specified buffer size
- Start a goroutine that iterates through the enumeration
- Send each element to the channel
- Close the channel when enumeration is complete
- Handle nil enumerators gracefully
Parameters:
bufferSize - the buffer size for the returned channel (0 for unbuffered)
Returns:
A read-only channel containing all elements from the enumeration
⚠️ Resource management: This operation starts a goroutine that runs until the enumeration is complete. Always consume all elements or the goroutine may block indefinitely.
⚠️ Blocking behavior: The goroutine will block when trying to send to a full channel if there's no reader. Use appropriate buffer size.
⚠️ Warning: If the returned channel is not fully consumed, the goroutine may leak. Always range over the entire channel or ensure proper cleanup.
Notes:
- If the enumerator is nil, returns a closed channel
- If the enumeration is empty, returns an empty but closed channel
- The goroutine automatically closes the channel when done
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(bufferSize) plus any upstream buffering
- The enumeration runs in a separate goroutine, enabling concurrent processing
func (EnumeratorAny[T]) ToSlice ¶
func (q EnumeratorAny[T]) ToSlice() []T
ToSlice converts an enumeration to a slice containing all elements. This operation is useful for materializing lazy enumerations into concrete collections.
The to slice operation will:
- Iterate through all elements in the enumeration
- Collect all elements into a new slice
- Return the slice containing all elements in order
- Handle nil enumerators gracefully
Returns:
A slice containing all elements from the enumeration, or empty slice if enumerator is nil
⚠️ Performance note: This is a terminal operation that must iterate through the entire enumeration to collect all elements. For large enumerations, this may be expensive in both time and memory.
⚠️ Memory note: This operation buffers all elements in memory.
Notes:
- If the enumerator is nil, returns an empty slice (not nil)
- If the enumeration is empty, returns an empty slice
- For very large enumerations, consider processing elements incrementally.
- Time complexity: O(n) where n is the number of elements
- Space complexity: O(n) - allocates memory for all elements
- The enumeration stops only when exhausted or if upstream operations stop it
- Returned slice preserves the order of elements from the enumeration
- Use with caution for infinite or very large enumerations
func (EnumeratorAny[T]) Where ¶
func (q EnumeratorAny[T]) Where(predicate func(T) bool) EnumeratorAny[T]
Where filters an enumeration based on a predicate function. This operation returns elements that satisfy the specified condition.
The where operation will:
- Apply the predicate function to each element in the enumeration
- Yield only elements for which the predicate returns true
- Preserve the original order of elements that pass the filter
- Handle nil enumerators gracefully
- Support early termination when consumer returns false
Parameters:
predicate - a function that determines whether to include an element
Returns:
An EnumeratorAny[T] that yields elements satisfying the predicate
Notes:
- If the original enumerator is nil, returns an empty enumerator
- Lazy evaluation - elements are processed and filtered during iteration
- No elements are buffered - memory efficient
- The enumeration stops when the source is exhausted or consumer returns false
- Predicate function should be pure (no side effects) for predictable behavior
- Elements for which predicate returns false are simply skipped
type MultipleElementsError ¶ added in v1.25.4
type MultipleElementsError struct {
// contains filtered or unexported fields
}
MultipleElementsError represents an error that occurs when an operation expects exactly one element in a sequence, but the sequence contains multiple elements.
func (*MultipleElementsError) Error ¶ added in v1.25.4
func (e *MultipleElementsError) Error() string
Error implements the error interface for MultipleElementsError. This method returns a string representation of the error that describes why the operation failed due to multiple elements in a sequence.
type NoElementsError ¶ added in v1.25.4
type NoElementsError struct {
// contains filtered or unexported fields
}
NoElementsError represents an error that occurs when an operation expects at least one element in a sequence, but the sequence is empty.
func (*NoElementsError) Error ¶ added in v1.25.4
func (e *NoElementsError) Error() string
Error implements the error interface for NoElementsError. This method returns a string representation of the error that describes why the operation failed due to an empty sequence.
type OrderEnumerator ¶ added in v1.25.7
type OrderEnumerator[T comparable] struct { // contains filtered or unexported fields }
OrderEnumerator represents an ordered sequence of elements that supports lazy sorting with multiple sorting levels. This type enables fluent chaining of sorting operations.
OrderEnumerator implements lazy evaluation pattern where:
- Sorting rules are accumulated when calling OrderBy/ThenBy methods
- Actual sorting computation is deferred until enumeration begins
- All sorting levels are applied in a single efficient pass during enumeration
The type supports:
- Primary sorting with OrderBy/OrderByDescending
- Secondary (and further) sorting with ThenBy/ThenByDescending
- Stable sorting that preserves relative order of equal elements
- Lazy evaluation with early termination support
- Zero memory allocation during rule accumulation
Type Parameters:
T - the comparable type of elements in the sequence (must satisfy comparable constraint)
⚠️ Performance characteristics:
- Rule accumulation: O(1) time, O(1) memory per operation
- Actual sorting: O(n log n) time, O(n) memory during first enumeration
- Subsequent enumerations: O(n log n) time, O(n) memory (sorting repeated)
- Early termination: supported, but full sort still required initially
⚠️ Memory usage:
- Rules storage: O(k) where k is number of sorting levels
- During sorting: O(n) for temporary storage of all elements
- After sorting: O(k) for rules, elements released
Notes:
- Type T must be comparable for proper sorting comparison
- All sorting levels are applied simultaneously during enumeration
- Sorting is stable - equal elements maintain relative order
- Source enumerator is consumed entirely during first enumeration
- Thread-safe for rule accumulation, but enumeration should be single-threaded
- Works seamlessly with other enumerable operations (Where, Take, Skip, etc.)
func (OrderEnumerator[T]) Contains ¶ added in v1.25.10
func (o OrderEnumerator[T]) Contains(value T) bool
Contains determines whether a sorted sequence contains a specified element using direct equality comparison. This operation is optimized for sorted sequences and leverages the ordering for efficient lookup.
The Contains operation will:
- Return true if the sorted sequence contains an element equal to the specified value
- Return false if the sorted sequence does not contain the specified value
- Return false if the enumerator is nil
- Use binary search for efficient lookup when applicable (based on sorting rules)
- Execute deferred sorting rules to determine the sorted order before searching
- Support early termination when element is found
Parameters:
value - the value to locate in the sorted sequence
Returns:
true if the sorted sequence contains an element equal to the specified value, false otherwise
⚠️ Performance note: This is a terminal operation that performs a binary search over the sorted sequence. Time complexity is O(n log n) for sorting + O(log n) for search, which results in O(n log n), where n is the number of elements.
⚠️ Memory note: This operation does not buffer elements beyond what is required for sorting. Sorting may require O(n) additional memory depending on the sorting algorithm used internally.
Notes:
- Uses direct equality comparison (==) for element comparison
- If enumerator is nil, returns false immediately
- Actual sorting computation occurs only once during the first enumeration or search
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Subsequent calls will re-execute sorting (sorting is not cached)
- This is a terminal operation that materializes the enumeration
- Efficient for large sorted sequences due to binary search
- Common use cases include fast membership testing in sorted data, validation logic, or conditional branching based on presence of values in sorted collections
func (OrderEnumerator[T]) Distinct ¶ added in v1.25.9
func (o OrderEnumerator[T]) Distinct() Enumerator[T]
Distinct returns an enumerator that yields only unique elements from a sorted sequence. This operation is optimized for sorted sequences and yields distinct elements in sorted order.
The Distinct operation will:
- Execute deferred sorting rules to determine the sorted order
- Yield each unique element exactly once in sorted order
- Preserve the order of elements according to the applied sorting rules
- Support early termination when consumer returns false
- Process elements sequentially with O(n) time complexity
Returns:
An Enumerator[T] that yields unique elements in sorted order
⚠️ Performance note: This is a streaming operation that processes elements sequentially and maintains only the previous element for comparison. Time complexity: O(n log n) for sorting + O(n) for distinct processing = O(n log n) where n is the number of elements.
⚠️ Memory note: This operation uses minimal additional memory - only stores the previous element for comparison. Memory usage is O(1) for processing, plus memory required for sorting. Space complexity: O(n) - allocates memory for all elements during sorting.
Notes:
- Requires T to be comparable (supports == operator)
- Uses Go's built-in equality operator (==) for element comparison
- For nil enumerators, returns empty enumerator
- Lazy evaluation - elements processed during iteration
- Elements are compared using Go's built-in equality after sorting
- Actual sorting computation occurs only during first enumeration
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- This is a streaming operation that does not buffer all elements in memory
- Works efficiently with sorted sequences by comparing only adjacent elements
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
- Common use cases include removing duplicates from sorted data, unique value extraction, or preparing data for further processing that requires uniqueness
func (OrderEnumerator[T]) ElementAt ¶ added in v1.25.7
func (o OrderEnumerator[T]) ElementAt(index int) (T, bool)
ElementAt returns the element at the specified index in the sorted sequence. This operation is useful when you need to access an element at a specific position in the sorted order without iterating through the entire sequence.
The ElementAt operation will:
- Execute deferred sorting rules and iterate through the sorted sequence
- Return the element at the specified zero-based index and true if found
- Return the zero value of T and false if index is negative
- Return the zero value of T and false if index is beyond the sequence bounds
- Return the zero value of T and false if the enumerator is nil
- Process elements sequentially until the specified index is reached in sorted order
Parameters:
index - the zero-based index of the element to retrieve from the sorted sequence
Returns:
The element at the specified index in sorted order and true if found, zero value of T and false otherwise
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. The operation must perform sorting and then iterate through the sorted sequence until the specified index is reached. Time complexity: O(n log n) for sorting + O(index + 1) for iteration = O(n log n) where n is the total number of elements.
⚠️ Memory note: This operation buffers all elements in memory during sorting, but does not buffer elements beyond the specified index during iteration. Space complexity: O(n) - allocates memory for all elements during sorting.
Notes:
- Index must be non-negative (negative indices return zero value and false)
- If index is beyond sequence bounds, returns zero value and false
- If enumerator is nil, returns zero value and false
- Actual sorting computation occurs only during this first operation
- Processes elements sequentially in sorted order - early termination when index is found
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- No elements are buffered beyond the target index - memory efficient for early indices
- This is a terminal operation that materializes the enumeration
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
func (OrderEnumerator[T]) FirstOrDefault ¶ added in v1.25.7
func (o OrderEnumerator[T]) FirstOrDefault(defaultValue T) T
FirstOrDefault returns the first element of a sorted enumeration in sorted order, or a default value if the enumeration is empty or nil.
The first or default operation will:
- Execute deferred sorting rules to determine the sorted order
- Return the first element from the enumeration in sorted order if it exists
- Return the provided default value if the enumeration is empty or nil
- Stop enumeration immediately after finding the first element
- Handle nil enumerators gracefully
Parameters:
defaultValue - the value to return if the enumeration is empty or nil
Returns:
The first element of the enumeration in sorted order, or the default value if enumeration is empty
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. The operation must perform sorting to determine the first element in sorted order. Time complexity: O(n log n) for sorting where n is the total number of elements.
⚠️ Memory note: This operation buffers all elements in memory during sorting. Space complexity: O(n) - allocates memory for all elements during sorting.
Notes:
- If the enumerator is nil, returns the defaultValue
- If the enumeration is empty, returns the defaultValue
- Actual sorting computation occurs only during this first operation
- Lazy evaluation stops immediately after finding the first element in sorted order
- This is a terminal operation that materializes the enumeration
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- No elements are buffered beyond the first element - memory efficient after sorting
- Unlike FirstOrNil(), this method returns the value directly, not a pointer
- Safe for all types including those with zero values like 0, "", false, etc.
- For sorted enumerations, this typically returns the minimum element according to sorting rules
- When using zero value as default, consider using FirstOrNil() for distinction
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
func (OrderEnumerator[T]) FirstOrNil ¶ added in v1.25.7
func (o OrderEnumerator[T]) FirstOrNil() *T
FirstOrNil returns a pointer to the first element of a sorted enumeration. This operation is useful for getting the first element in sorted order when it exists, with the ability to distinguish between "no elements" and "zero value" cases.
The first operation will:
- Execute deferred sorting rules to determine the sorted order
- Return a pointer to the first element in sorted order if the enumeration contains elements
- Return nil if the enumeration is empty or nil
- Stop enumeration immediately after finding the first element
- Handle nil enumerators gracefully
Returns:
A pointer to the first element in sorted order, or nil if enumeration is empty or nil
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. The operation must perform sorting to determine the first element in sorted order. Time complexity: O(n log n) for sorting where n is the total number of elements.
⚠️ Memory note: This operation buffers all elements in memory during sorting. Space complexity: O(n) - allocates memory for all elements during sorting.
Notes:
- If the enumerator is nil, returns nil
- If the enumeration is empty, returns nil
- Actual sorting computation occurs only during this first operation
- Lazy evaluation stops immediately after finding the first element in sorted order
- This is a terminal operation that materializes the enumeration
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- No elements are buffered beyond the first element - memory efficient after sorting
- Returns pointer to allow distinction between "no elements" (nil) and "zero value" element
- Safe for all types including those with zero values like 0, "", false, etc.
- For sorted enumerations, this typically returns the minimum element according to sorting rules
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
func (OrderEnumerator[T]) LastOrDefault ¶ added in v1.25.7
func (o OrderEnumerator[T]) LastOrDefault(defaultValue T) T
LastOrDefault returns the last element of a sorted enumeration in sorted order, or a default value if the enumeration is empty or nil.
The last or default operation will:
- Execute deferred sorting rules to determine the sorted order
- Iterate through all elements in the sorted enumeration
- Keep track of the most recent element encountered in sorted order
- Return the last element if enumeration contains elements
- Return the provided default value if the enumeration is empty or nil
- Handle nil enumerators gracefully
Parameters:
defaultValue - the value to return if the enumeration is empty or nil
Returns:
The last element of the enumeration in sorted order, or the default value if enumeration is empty
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation and must iterate through the entire sorted enumeration to find the last element. Time complexity: O(n log n) for sorting + O(n) for iteration = O(n log n) where n is the number of elements. For large enumerations, this may be expensive.
⚠️ Memory note: This operation buffers all elements in memory during sorting, but does not buffer elements beyond tracking the last element during iteration. Space complexity: O(n) - allocates memory for all elements during sorting.
Notes:
- If the enumerator is nil, returns the defaultValue
- If the enumeration is empty, returns the defaultValue
- Actual sorting computation occurs only during this first operation
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Time complexity: O(n log n) where n is the number of elements
- Space complexity: O(n) during sorting, O(1) during iteration
- Unlike LastOrNil(), this method returns the value directly, not a pointer
- Safe for all types including those with zero values like 0, "", false, etc.
- For sorted enumerations, this typically returns the maximum element according to sorting rules
- When using zero value as default, consider using LastOrNil() for distinction
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
func (OrderEnumerator[T]) LastOrNil ¶ added in v1.25.7
func (o OrderEnumerator[T]) LastOrNil() *T
LastOrNil returns a pointer to the last element of a sorted enumeration in sorted order, or nil if the enumeration is empty or nil.
The last or nil operation will:
- Execute deferred sorting rules to determine the sorted order
- Iterate through all elements in the sorted enumeration
- Keep track of the most recent element encountered in sorted order
- Return a pointer to the last element if enumeration contains elements
- Return nil if the enumeration is empty or nil
- Handle nil enumerators gracefully
Returns:
A pointer to the last element in sorted order, or nil if enumeration is empty or nil
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation and must iterate through the entire sorted enumeration to find the last element. Time complexity: O(n log n) for sorting + O(n) for iteration = O(n log n) where n is the number of elements. For large enumerations, this may be expensive.
⚠️ Memory note: This operation buffers all elements in memory during sorting, but does not buffer elements beyond tracking the last element during iteration. Space complexity: O(n) - allocates memory for all elements during sorting.
Notes:
- If the enumerator is nil, returns nil
- If the enumeration is empty, returns nil
- Actual sorting computation occurs only during this first operation
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Time complexity: O(n log n) where n is the number of elements
- Space complexity: O(n) during sorting, O(1) during iteration
- Returns pointer to allow distinction between "no elements" (nil) and "zero value" element
- Safe for all types including those with zero values like 0, "", false, etc.
- For sorted enumerations, this typically returns the maximum element according to sorting rules
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
func (OrderEnumerator[T]) Single ¶ added in v1.25.7
func (o OrderEnumerator[T]) Single() (T, error)
Single returns the single element of a sorted sequence using default equality comparison. This operation is useful when you expect exactly one element in the sorted sequence.
The Single operation will:
- Execute deferred sorting rules to determine the sorted order
- Return the single element if the sequence contains exactly one element
- Return an error if the sequence is empty ("sequence contains no elements")
- Return an error if the sequence contains more than one element ("sequence contains more than one element")
- Process elements sequentially until completion or error
- Handle nil enumerators gracefully
Returns:
The single element of the sequence and nil error if successful, zero value of T and error otherwise
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation and must iterate through the sequence until completion or error. For large sequences with multiple elements, this may process more elements than necessary. Time complexity: O(n log n) for sorting + O(n) for validation = O(n log n) where n is the number of elements.
⚠️ Memory note: This operation buffers all elements in memory during sorting, but it does not buffer elements beyond validation during iteration. Space complexity: O(n) - allocates memory for all elements during sorting.
Notes:
- If the enumerator is nil, returns zero value and error ("sequence contains no elements")
- If the enumeration is empty, returns zero value and error ("sequence contains no elements")
- If the enumeration contains more than one element, returns zero value and error ("sequence contains more than one element")
- Actual sorting computation occurs only during this first operation
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Processes elements in the enumeration - O(n log n) time complexity in worst case
- No elements are buffered beyond sorting phase - memory efficient after sorting
- This is a terminal operation that materializes the enumeration
- Works only with comparable types (no slices, maps, functions in struct fields)
- The type T must be comparable for equality comparison to work
- For large enumerations, all elements may be processed to ensure uniqueness
- This method should be used when you are certain the sequence contains exactly one element
- Common use cases include lookup by unique identifier or configuration validation
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
func (OrderEnumerator[T]) SingleBy ¶ added in v1.25.7
func (o OrderEnumerator[T]) SingleBy(comparer comparer.EqualityComparer[T]) (T, error)
SingleBy returns the single element of a sorted sequence that satisfies the provided equality comparer. This operation is useful when you expect exactly one element in the sorted sequence and need custom equality logic.
The SingleBy operation will:
- Execute deferred sorting rules to determine the sorted order
- Return the single element if the sequence contains exactly one distinct element according to the comparer
- Return an error if the sequence is empty ("sequence contains no elements")
- Return an error if the sequence contains more than one distinct element according to the comparer
- Process elements sequentially until completion or second distinct element found
- Handle nil enumerators gracefully
Parameters:
comparer - an EqualityComparer that defines when two elements are considered equal
Returns:
The single element of the sequence and nil error if successful, zero value of T and error otherwise
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation and must iterate through the sequence until completion or second distinct element found. For large sequences with multiple distinct elements, this may process more elements than necessary. Time complexity: O(n log n) for sorting + O(n) for validation = O(n log n) where n is the number of elements processed.
⚠️ Memory note: This operation buffers all elements in memory during sorting, and buffers elements to perform equality comparison using hash-based lookup. Memory usage depends on the number of distinct elements encountered during processing. Space complexity: O(n) - allocates memory for all elements during sorting and comparison.
Notes:
- If the enumerator is nil, returns zero value and error ("sequence contains no elements")
- If the enumeration is empty, returns zero value and error ("sequence contains no elements")
- If the enumeration contains more than one distinct element, returns zero value and error ("sequence contains more than one element")
- Actual sorting computation occurs only during this first operation
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Uses the provided comparer's Equals and GetHashCode methods for efficient element comparison
- Elements are buffered in hash buckets during comparison for efficient duplicate detection
- This is a terminal operation that materializes the enumeration
- Works with comparable types when used with appropriate comparer
- The comparer functions must be consistent and deterministic
- For large enumerations, processing stops early when second distinct element is found
- This method should be used when you are certain the sequence contains exactly one distinct element
- Common use cases include lookup by custom equality logic, complex object comparison, or unique constraint validation
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
func (OrderEnumerator[T]) SingleOrDefault ¶ added in v1.25.7
func (o OrderEnumerator[T]) SingleOrDefault(defaultValue T) T
SingleOrDefault returns the single element of a sorted sequence using default equality comparison, or a specified default value if the sequence is empty.
The SingleOrDefault operation will:
- Execute deferred sorting rules to determine the sorted order
- Return the single element if the sequence contains exactly one element
- Return the specified default value if the sequence is empty (including nil enumerator)
- Return the specified default value if the sequence contains more than one element
- Process elements sequentially until completion or second element found
- Handle nil enumerators gracefully (treated as empty)
Returns:
The single element of the sequence if successful, or the specified default value otherwise
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation and must iterate through the sequence until completion or second element found. For large sequences with multiple elements, this may process more elements than necessary. Time complexity: O(n log n) for sorting + O(n) for validation = O(n log n) where n is the number of elements.
⚠️ Memory note: This operation buffers all elements in memory during sorting, but it does not buffer elements beyond validation during iteration. Space complexity: O(n) - allocates memory for all elements during sorting.
Notes:
- If the enumerator is nil, returns the specified default value
- If the enumeration is empty, returns the specified default value
- If the enumeration contains more than one element, returns the specified default value
- Actual sorting computation occurs only during this first operation
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Processes elements in the enumeration - O(n log n) time complexity in worst case
- No elements are buffered beyond sorting phase - memory efficient after sorting
- This is a terminal operation that materializes the enumeration
- Works only with comparable types (no slices, maps, functions in struct fields)
- The type T must be comparable for equality comparison to work
- For large enumerations, elements may be processed to detect multiple items
- This method should be used when you expect zero or one element, with fallback for other cases
- Common use cases include optional lookup by unique identifier or configuration with defaults
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
⚠️ Important: Unlike Single(), this method never returns an error. All error conditions (empty sequence, multiple elements) result in returning the default value. If you need to distinguish between these cases, use Single() instead.
func (OrderEnumerator[T]) Skip ¶ added in v1.25.7
func (o OrderEnumerator[T]) Skip(n int) Enumerator[T]
Skip bypasses a specified number of elements in a sorted enumeration and then yields the remaining elements in sorted order. This operation is useful for pagination, skipping headers, or bypassing initial elements in the context of sorted sequences.
The skip operation will:
- Execute deferred sorting rules to determine the sorted order
- Bypass the first n elements from the sorted enumeration
- Yield all remaining elements in sorted order
- Handle edge cases gracefully (n <= 0, n >= count)
- Support early termination when consumer returns false
Parameters:
n - the number of elements to skip (must be non-negative)
Returns:
An Enumerator[T] that yields elements in sorted order after skipping the first n elements
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. Time complexity: O(n log n) for sorting where n is the total number of elements. The skip operation itself is O(1) - elements are skipped during iteration. For large enumerations, this may process more elements than necessary.
⚠️ Memory note: This operation buffers all elements in memory during sorting. Space complexity: O(n) - allocates memory for all elements during sorting. No additional buffering beyond sorting phase.
Notes:
- If n <= 0, returns an enumerator that yields all elements in sorted order
- If n >= total number of elements, returns an empty enumerator
- If the original enumerator is nil, returns an empty enumerator (not nil)
- Actual sorting computation occurs only during first enumeration
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Lazy evaluation - elements are processed and skipped during iteration
- No elements are buffered beyond sorting phase - memory efficient after sorting
- Negative values of n are treated as 0
- The enumeration is consumed sequentially, so skipped elements are still processed during sorting
- Elements are yielded in sorted order according to all accumulated sorting rules
- Subsequent enumerations will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
func (OrderEnumerator[T]) SkipLast ¶ added in v1.25.7
func (o OrderEnumerator[T]) SkipLast(n int) Enumerator[T]
SkipLast bypasses a specified number of elements at the end of a sorted enumeration and yields the remaining elements in sorted order. This operation is useful for removing trailing elements like footers, summaries, or fixed-size endings from sorted sequences.
The skip last operation will:
- Execute deferred sorting rules to determine the sorted order
- Buffer elements to track which are the final n elements in sorted order
- Yield elements only after confirming they are not among the last n in sorted order
- Handle edge cases gracefully (n <= 0, n >= count)
- Support early termination when consumer returns false
Parameters:
n - the number of elements to skip from the end (must be non-negative)
Returns:
An Enumerator[T] that yields elements in sorted order except the last n elements
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. This operation buffers up to n elements in memory using a circular buffer for efficient memory usage. Time complexity: O(n log n) for sorting where n is the total number of elements. For large values of n, this may consume significant memory.
⚠️ Evaluation note: This operation is partially lazy - elements are processed as the enumeration proceeds, but the last n elements are buffered and never yielded. The enumeration must progress beyond n elements to yield earlier ones. Actual sorting computation occurs only during enumeration.
⚠️ Memory note: This operation buffers all elements in memory during sorting, plus additional buffering of up to n elements for the skip operation. Space complexity: O(m + n) where m is total elements and n is skip count.
Notes:
- If n <= 0, returns an enumerator that yields all elements in sorted order
- If n >= total number of elements, returns an empty enumerator
- If the original enumerator is nil, returns an empty enumerator
- Elements are yielded in sorted order according to all accumulated sorting rules
- Actual sorting computation occurs only during first enumeration
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Subsequent enumerations will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
func (OrderEnumerator[T]) SkipWhile ¶ added in v1.25.7
func (o OrderEnumerator[T]) SkipWhile(predicate func(T) bool) Enumerator[T]
SkipWhile bypasses elements in a sorted enumeration as long as a specified condition is true and then yields the remaining elements in sorted order. This operation is useful for skipping elements until a certain condition is met in the context of sorted sequences.
The skip while operation will:
- Execute deferred sorting rules to determine the sorted order
- Bypass elements from the beginning while the predicate returns true
- Once the predicate returns false for an element, yield that element and all subsequent elements
- Support early termination when consumer returns false
Parameters:
predicate - a function that determines whether to skip an element
Returns:
An Enumerator[T] that yields elements in sorted order after skipping initial elements that match the condition
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. Time complexity: O(n log n) for sorting where n is the total number of elements. The predicate is evaluated during iteration after sorting is complete.
⚠️ Memory note: This operation buffers all elements in memory during sorting. Space complexity: O(n) - allocates memory for all elements during sorting. No additional buffering beyond sorting phase.
Notes:
- If the predicate never returns false, returns an empty enumerator
- If the predicate immediately returns false for the first element, returns all elements in sorted order
- If the original enumerator is nil, returns an empty enumerator
- Actual sorting computation occurs only during first enumeration
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Lazy evaluation - elements are processed and evaluated during iteration
- The enumeration stops skipping as soon as the first non-matching element is found
- Once skipping stops, all remaining elements are yielded (even if they would match the predicate)
- Elements are yielded in sorted order according to all accumulated sorting rules
- Subsequent enumerations will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
func (OrderEnumerator[T]) Take ¶ added in v1.25.7
func (o OrderEnumerator[T]) Take(n int) Enumerator[T]
Take returns a specified number of contiguous elements from the start of a sorted enumeration in sorted order. This operation is useful for pagination, limiting results, or taking samples from sorted sequences.
The take operation will:
- Execute deferred sorting rules to determine the sorted order
- Yield the first n elements from the sorted enumeration
- Stop enumeration once n elements have been yielded
- Handle edge cases gracefully (n <= 0, n >= count)
- Support early termination when consumer returns false
Parameters:
n - the number of elements to take (must be non-negative)
Returns:
An Enumerator[T] that yields at most n elements from the start in sorted order
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. Time complexity: O(n log n) for sorting where n is the total number of elements. The take operation itself is O(1) - elements are taken during iteration. For large enumerations where n << total, this may process more elements than necessary.
⚠️ Memory note: This operation buffers all elements in memory during sorting. Space complexity: O(n) - allocates memory for all elements during sorting. No additional buffering beyond sorting phase.
Notes:
- If n <= 0, returns an empty enumerator
- If n >= total number of elements, returns all available elements in sorted order
- If the original enumerator is nil, returns an empty enumerator
- Actual sorting computation occurs only during first enumeration
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Lazy evaluation - elements are processed and yielded during iteration
- No elements are buffered beyond sorting phase - memory efficient after sorting
- Negative values of n are treated as 0
- Early termination by the consumer stops further enumeration
- The enumeration stops as soon as n elements are yielded or the source is exhausted
- Elements are yielded in sorted order according to all accumulated sorting rules
- Subsequent enumerations will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
func (OrderEnumerator[T]) TakeLast ¶ added in v1.25.7
func (o OrderEnumerator[T]) TakeLast(n int) Enumerator[T]
TakeLast returns a specified number of contiguous elements from the end of a sorted enumeration in sorted order. This operation is useful for getting the final elements, such as last N records, trailing averages, or end-of-sequence markers from sorted sequences.
The take last operation will:
- Execute deferred sorting rules to determine the sorted order
- Buffer elements to track the last n elements seen so far in sorted order
- Yield the final n elements when enumeration completes
- Handle edge cases gracefully (n <= 0, n >= count)
- Support early termination when consumer returns false
Parameters:
n - the number of elements to take from the end (must be non-negative)
Returns:
An Enumerator[T] that yields the last n elements in sorted order
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. This operation buffers up to n elements in memory to track which elements should be yielded. Time complexity: O(n log n) for sorting where n is the total number of elements. For large values of n, this may consume significant memory. All elements must be processed before any are yielded.
⚠️ Evaluation note: This operation is not lazy in the traditional sense - the entire source enumeration must be consumed and sorted before yielding begins. Elements are yielded in sorted order according to all accumulated sorting rules.
⚠️ Memory note: This operation buffers all elements in memory during sorting, plus additional buffering of up to n elements for the take operation. Space complexity: O(m + n) where m is total elements and n is take count.
Notes:
- If n <= 0, returns an empty enumerator
- If n >= total number of elements, returns all available elements in sorted order
- If the original enumerator is nil, returns an empty enumerator
- Actual sorting computation occurs only during first enumeration
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Negative values of n are treated as 0
- The enumeration stops as soon as the consumer returns false
- Elements are yielded in sorted order according to all accumulated sorting rules
- Subsequent enumerations will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
func (OrderEnumerator[T]) TakeWhile ¶ added in v1.25.7
func (o OrderEnumerator[T]) TakeWhile(predicate func(T) bool) Enumerator[T]
TakeWhile returns elements from a sorted enumeration as long as a specified condition is true. This operation is useful for taking elements until a certain condition is met, such as taking elements while they are valid or within a range, in the context of sorted sequences.
The take while operation will:
- Execute deferred sorting rules to determine the sorted order
- Yield elements from the start while the predicate returns true
- Stop enumeration as soon as the predicate returns false for an element
- Handle edge cases gracefully (nil enumerator, always false predicate)
- Support early termination when consumer returns false
Parameters:
predicate - a function that determines whether to take an element
Returns:
An Enumerator[T] that yields elements in sorted order while the condition is true
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. Time complexity: O(n log n) for sorting where n is the total number of elements. The predicate evaluation is O(1) per element during iteration. For large enumerations, this may process more elements than necessary.
⚠️ Memory note: This operation buffers all elements in memory during sorting. Space complexity: O(n) - allocates memory for all elements during sorting. No additional buffering beyond sorting phase.
Notes:
- If the predicate immediately returns false for the first element, returns empty enumerator
- If the predicate never returns false, returns all elements from the sorted enumeration
- If the original enumerator is nil, returns an empty enumerator
- Actual sorting computation occurs only during first enumeration
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Lazy evaluation - elements are processed and evaluated during iteration
- No elements are buffered beyond sorting phase - memory efficient after sorting
- The enumeration stops as soon as the predicate returns false or consumer returns false
- Once the predicate returns false for any element, no subsequent elements are evaluated
- Elements are yielded in sorted order according to all accumulated sorting rules
- Subsequent enumerations will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
func (OrderEnumerator[T]) ThenBy ¶ added in v1.25.7
func (o OrderEnumerator[T]) ThenBy(comparer comparer.ComparerFunc[T]) OrderEnumerator[T]
ThenBy performs a subsequent ordering of the elements in ascending order according to a comparer function. This method adds a secondary (or further) sorting level to an existing ordered sequence.
The ThenBy operation:
- Accumulates additional sorting rules without immediate execution (lazy evaluation)
- Returns an OrderEnumerator that supports further chaining with additional ThenBy operations
- Uses the provided comparer function to determine secondary element ordering
- Maintains stable sorting (equal elements preserve relative order)
- Works with comparable types using direct comparison
Parameters:
comparer - a ComparerFunc that defines the secondary sort order by comparing two elements of type T
The function should return:
< 0 if first element is less than second
= 0 if elements are equal
> 0 if first element is greater than second
Returns:
An OrderEnumerator[T] that contains elements sorted by both primary and secondary criteria
⚠️ Performance note: This is a deferred execution operation that accumulates sorting rules. Actual sorting computation occurs during first enumeration. Time complexity: O(1) for rule accumulation, O(n log n) for actual sorting during enumeration with all accumulated rules.
Notes:
- This is a lazy operation - no sorting occurs until enumeration begins
- Can be chained multiple times to create multiple sorting levels
- Each ThenBy adds a new sorting level with lower priority than previous levels
- The comparer function must be deterministic and consistent
- Works with both comparable and non-comparable types through appropriate comparer functions
- Thread-safe for rule accumulation, but enumeration should be single-threaded
func (OrderEnumerator[T]) ThenByDescending ¶ added in v1.25.7
func (o OrderEnumerator[T]) ThenByDescending(comparer comparer.ComparerFunc[T]) OrderEnumerator[T]
ThenByDescending performs a subsequent ordering of the elements in descending order according to a comparer function. This method adds a secondary (or further) sorting level to an existing ordered sequence in reverse order.
The ThenByDescending operation:
- Accumulates additional sorting rules without immediate execution (lazy evaluation)
- Returns an OrderEnumerator that supports further chaining with additional ThenBy operations
- Uses the provided comparer function to determine secondary element ordering (reversed)
- Maintains stable sorting (equal elements preserve relative order)
- Works with comparable types using direct comparison
Parameters:
comparer - a ComparerFunc that defines the secondary sort order by comparing two elements of type T
The function should return:
< 0 if first element is less than second
= 0 if elements are equal
> 0 if first element is greater than second
Note: The final order for this level will be reversed (descending)
Returns:
An OrderEnumerator[T] that contains elements sorted by both primary and secondary criteria
⚠️ Performance note: This is a deferred execution operation that accumulates sorting rules. Actual sorting computation occurs during first enumeration. Time complexity: O(1) for rule accumulation, O(n log n) for actual sorting during enumeration with all accumulated rules.
Notes:
- This is a lazy operation - no sorting occurs until enumeration begins
- Can be chained multiple times to create multiple sorting levels
- Each ThenByDescending adds a new sorting level with lower priority than previous levels
- The comparer function must be deterministic and consistent
- Works with both comparable and non-comparable types through appropriate comparer functions
- Thread-safe for rule accumulation, but enumeration should be single-threaded
func (OrderEnumerator[T]) ToBatch ¶ added in v1.25.8
func (e OrderEnumerator[T]) ToBatch(batchSize int) [][]T
ToBatch groups elements from a sorted enumeration into batches of specified size and returns them as a slice of slices in sorted order. This operation is useful for processing large sorted sequences in chunks, implementing pagination, or optimizing batch operations on sorted data.
The to batch operation will:
- Execute deferred sorting rules to determine the sorted order
- Group consecutive elements in sorted order into slices of at most batchSize elements
- Return all batches as a slice when enumeration is complete
- Handle edge cases gracefully (batchSize <= 0, empty source)
- Materialize the entire sorted enumeration (terminal operation)
Parameters:
batchSize - the maximum number of elements per batch (must be positive)
Returns:
A slice containing batches of elements in sorted order, or empty slice if no batches
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation and must iterate through the entire sorted enumeration to create all batches. Time complexity: O(n log n) for sorting + O(n) for batching = O(n log n) where n is the number of elements.
⚠️ Memory note: This operation buffers all elements in memory during sorting, plus additional buffering for batching. Space complexity: O(n) where n is total elements.
⚠️ Evaluation note: This operation is not lazy in the traditional sense - actual sorting computation occurs immediately upon calling this method. All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting.
Notes:
- If batchSize <= 0, returns empty slice
- If the original enumerator is nil, returns empty slice
- Last batch may contain fewer elements than batchSize
- Terminal operation - consumes entire sorted enumeration
- Each batch is a separate slice - safe for modification
- No elements are lost - all elements from source are included in batches
- Actual sorting computation occurs only during this operation
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Elements are grouped in sorted order according to all accumulated sorting rules
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
func (OrderEnumerator[T]) ToChannel ¶ added in v1.25.7
func (o OrderEnumerator[T]) ToChannel(bufferSize int) <-chan T
ToChannel converts a sorted enumeration to a channel that yields all elements in sorted order. This operation is useful for converting lazy sorted enumerations into channel-based processing pipelines or for interoperability with goroutines.
The to channel operation will:
- Execute deferred sorting rules to determine the sorted order
- Create a new channel with specified buffer size
- Start a goroutine that iterates through the sorted enumeration
- Send each element to the channel in sorted order
- Close the channel when enumeration is complete
- Handle nil enumerators gracefully
Parameters:
bufferSize - the buffer size for the returned channel (0 for unbuffered)
Returns:
A read-only channel containing all elements from the enumeration in sorted order
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. Time complexity: O(n log n) for sorting where n is the total number of elements. The channel creation and goroutine startup is O(1). For large enumerations, this may process more elements than necessary.
⚠️ Memory note: This operation buffers all elements in memory during sorting. Space complexity: O(n) - allocates memory for all elements during sorting. Plus O(bufferSize) for the channel buffer.
⚠️ Resource management: This operation starts a goroutine that runs until the enumeration is complete. Always consume all elements or the goroutine may block indefinitely.
⚠️ Blocking behavior: The goroutine will block when trying to send to a full channel if there's no reader. Use appropriate buffer size.
⚠️ Warning: If the returned channel is not fully consumed, the goroutine may leak. Always range over the entire channel or ensure proper cleanup.
Notes:
- If the enumerator is nil, returns a closed channel
- If the enumeration is empty, returns an empty but closed channel
- Actual sorting computation occurs only during first enumeration
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- The goroutine automatically closes the channel when done
- Time complexity: O(n log n) where n is the number of elements
- Space complexity: O(n + bufferSize) for sorting plus channel buffering
- The enumeration runs in a separate goroutine, enabling concurrent processing
- Elements are yielded in sorted order according to all accumulated sorting rules
- Subsequent enumerations will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
func (OrderEnumerator[T]) ToMap ¶ added in v1.25.7
func (o OrderEnumerator[T]) ToMap() map[T]struct{}
ToMap converts a sorted enumeration to a map[T]struct{} for efficient set-like operations. This operation is useful for creating memory-efficient lookup collections or for removing duplicates while materializing a sorted enumeration.
The to map operation will:
- Execute deferred sorting rules to determine the sorted order
- Iterate through all elements in the sorted enumeration
- Add each element as a key in the resulting map with empty struct value
- Automatically remove duplicates (map key uniqueness)
- Return the resulting map
- Handle nil enumerators gracefully by returning an empty map
Returns:
A map[T]struct{} containing all unique elements as keys in sorted order,
or an empty map if enumerator is nil or enumeration is empty
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation and must iterate through the entire sorted enumeration. Time complexity: O(n log n) for sorting + O(n) for map creation = O(n log n) where n is the number of elements. For large enumerations, this may be expensive.
⚠️ Memory note: This operation buffers all elements in memory during sorting, plus all unique elements in the resulting map. Space complexity: O(n) for sorting + O(k) for map where k is unique elements.
⚠️ Evaluation note: This operation is not lazy - actual sorting computation occurs immediately upon calling this method. All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting.
Notes:
- If the enumerator is nil, returns an empty map (not nil)
- If the enumeration is empty, returns an empty map
- Automatically removes duplicates due to map key uniqueness
- Uses map[T]struct{} for memory efficiency (struct{} takes zero memory)
- Time complexity: O(n log n) where n is the number of elements
- Space complexity: O(n + k) where n is total elements and k is unique elements
- Keys in the returned map are the unique elements from the sorted enumeration
- Values in the returned map are empty structs (zero memory footprint)
- Check for element presence using: if _, exists := map[key]; exists { ... }
- More memory-efficient than map[T]bool since struct{} takes no memory
- Always returns a valid map, never nil - safe for immediate use
- Actual sorting computation occurs only during this operation
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Elements are added to map in sorted order according to all accumulated sorting rules
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
func (OrderEnumerator[T]) ToSlice ¶ added in v1.25.7
func (o OrderEnumerator[T]) ToSlice() []T
ToSlice converts an ordered enumeration to a slice containing all elements in sorted order. This operation is useful for materializing lazy ordered enumerations into concrete sorted collections.
The to slice operation will:
- Execute deferred sorting rules and iterate through all elements in sorted order
- Collect all elements into a new slice preserving the sorted order
- Return the slice containing all elements in their sorted positions
- Handle nil enumerators gracefully
Returns:
A slice containing all elements from the enumeration in sorted order, or empty slice if enumerator is nil
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. The operation must iterate through the entire enumeration and perform sorting. Time complexity: O(n log n) for sorting + O(n) for collection = O(n log n). For large enumerations, this may be expensive in both time and memory.
⚠️ Memory note: This operation buffers all elements in memory during sorting and collection. Space complexity: O(n) - allocates memory for all elements plus temporary sorting storage.
Notes:
- If the enumerator is nil, returns an empty slice (not nil)
- If the enumeration is empty, returns an empty slice
- Sorting is performed according to all accumulated sorting rules (OrderBy + ThenBy levels)
- The returned slice preserves the fully sorted order of elements
- Actual sorting computation occurs only during this first materialization
- Subsequent calls will re-execute sorting (sorting is not cached)
- Use with caution for infinite or very large enumerations
- Stable sorting preserves relative order of equal elements according to sorting rules
type OrderEnumeratorAny ¶ added in v1.25.7
type OrderEnumeratorAny[T any] struct { // contains filtered or unexported fields }
OrderEnumeratorAny represents an ordered sequence of elements for any type T, including non-comparable types, that supports lazy sorting with multiple sorting levels. This type enables fluent chaining of sorting operations for complex types.
OrderEnumeratorAny implements lazy evaluation pattern where:
- Sorting rules are accumulated when calling OrderBy/ThenBy methods
- Actual sorting computation is deferred until enumeration begins
- All sorting levels are applied in a single efficient pass during enumeration
The type supports:
- Primary sorting with OrderBy/OrderByDescending using custom comparers
- Secondary (and further) sorting with ThenBy/ThenByDescending
- Stable sorting that preserves relative order of equal elements
- Lazy evaluation with early termination support
- Zero memory allocation during rule accumulation
- Full compatibility with non-comparable types (structs with slices, maps, functions)
Type Parameters:
T - any type of elements in the sequence (including non-comparable types)
⚠️ Performance characteristics:
- Rule accumulation: O(1) time, O(1) memory per operation
- Actual sorting: O(n log n) time, O(n) memory during first enumeration
- Subsequent enumerations: O(n log n) time, O(n) memory (sorting repeated)
- Early termination: supported, but full sort still required initially
⚠️ Memory usage:
- Rules storage: O(k) where k is number of sorting levels
- During sorting: O(n) for temporary storage of all elements
- After sorting: O(k) for rules, elements released
Notes:
- Works with any type T, including non-comparable types
- Custom comparer functions must implement proper comparison logic
- Comparer functions should be deterministic and consistent
- All sorting levels are applied simultaneously during enumeration
- Sorting is stable - equal elements maintain relative order
- Source enumerator is consumed entirely during the first enumeration
- Thread-safe for rule accumulation, but enumeration should be single-threaded
- Works seamlessly with other enumerable operations (Where, Take, Skip, etc.)
- More flexible than OrderEnumerator[T comparable] but potentially slower for simple types
func (OrderEnumeratorAny[T]) Contains ¶ added in v1.25.10
func (o OrderEnumeratorAny[T]) Contains(value T, comparer comparer.EqualityComparer[T]) bool
Contains determines whether a sorted sequence contains a specified element using the provided equality comparer. This operation is optimized for sorted sequences and leverages the ordering for efficient lookup with custom equality logic.
The Contains operation will:
- Return true if the sorted sequence contains an element equal to the specified value according to the comparer
- Return false if the sorted sequence does not contain the specified value
- Return false if the enumerator is nil
- Return false if the comparer is nil
- Use binary search for efficient lookup when applicable (based on sorting rules)
- Execute deferred sorting rules to determine the sorted order before searching
- Support early termination when element is found
- Use the provided equality comparer for element comparison
Parameters:
value - the value to locate in the sorted sequence comparer - the EqualityComparer to use for element comparison
Returns:
true if the sorted sequence contains an element equal to the specified value, false otherwise
⚠️ Performance note: This is a terminal operation that performs a binary search over the sorted sequence. Time complexity is O(n log n) for sorting + O(log n) for search, which results in O(n log n), where n is the number of elements.
⚠️ Memory note: This operation does not buffer elements beyond what is required for sorting. Sorting may require O(n) additional memory depending on the sorting algorithm used internally.
Notes:
- Uses the provided equality comparer for comparison
- If enumerator is nil, returns false immediately
- If comparer is nil, returns false immediately
- Actual sorting computation occurs only once during the first enumeration or search
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Subsequent calls will re-execute sorting (sorting is not cached)
- This is a terminal operation that materializes the enumeration
- Works with any type T (including non-comparable types) when used with appropriate comparer
- Efficient for large sorted sequences due to binary search
- Common use cases include fast membership testing in sorted data with custom equality logic, validation logic, or conditional branching based on presence of values in sorted collections
func (OrderEnumeratorAny[T]) Distinct ¶ added in v1.25.9
func (o OrderEnumeratorAny[T]) Distinct(comparer comparer.EqualityComparer[T]) EnumeratorAny[T]
Distinct returns an enumerator that yields only unique elements from a sorted sequence using a custom equality comparer to determine uniqueness. This operation is optimized for sorted sequences and yields distinct elements in sorted order.
The Distinct operation will:
- Execute deferred sorting rules to determine the sorted order
- Yield each unique element exactly once in sorted order
- Preserve the order of elements according to the applied sorting rules
- Support early termination when consumer returns false
- Process elements sequentially with O(n) time complexity
Parameters:
comparer - an EqualityComparer that defines when two elements are considered equal
Returns:
An EnumeratorAny[T] that yields unique elements in sorted order
⚠️ Performance note: This is a streaming operation that processes elements sequentially and maintains only the previous element for comparison. Time complexity: O(n log n) for sorting + O(n) for distinct processing = O(n log n) where n is the number of elements.
⚠️ Performance warning: This operation can be significantly slower than Distinct() for comparable types due to the overhead of EqualityComparer interface calls and hash-based collision resolution. Consider using Distinct() with comparable types when possible for better performance.
⚠️ Allocation warning: This operation performs multiple memory allocations during execution, especially for enumerations with many unique elements. Each unique element requires storage in internal hash buckets, leading to increased GC pressure.
⚠️ Memory note: This operation uses minimal additional memory - only stores the previous element for comparison and hash buckets for efficient equality checking. Memory usage depends on the comparer implementation and element size. Space complexity: O(n) - allocates memory for all elements during sorting.
Notes:
- Uses the provided comparer's Equals and GetHashCode methods for element comparison
- For nil enumerators, returns empty enumerator
- Lazy evaluation - elements processed during iteration
- Elements are compared using the provided EqualityComparer after sorting
- Actual sorting computation occurs only during first enumeration
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- This is a streaming operation that does not buffer all elements in memory
- Works efficiently with sorted sequences by comparing only adjacent elements
- The comparer must not be nil, or the operation will panic
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
- Common use cases include removing duplicates from sorted data with custom equality logic, unique value extraction for complex objects, or preparing data for further processing
- Elements are buffered in hash buckets during comparison for efficient duplicate detection
- This method is particularly useful when default equality comparison is insufficient
- Time complexity: O(n log n) average case for sorting + O(n) for distinct processing
- Space complexity: O(k) where k is the number of unique elements during distinct processing
func (OrderEnumeratorAny[T]) ElementAt ¶ added in v1.25.7
func (o OrderEnumeratorAny[T]) ElementAt(index int) (T, bool)
ElementAt returns the element at the specified index in the sorted sequence. This operation is useful when you need to access an element at a specific position in the sorted order without iterating through the entire sequence. This method supports any type T, including non-comparable types with custom sorting logic.
The ElementAt operation will:
- Execute deferred sorting rules and iterate through the sorted sequence
- Return the element at the specified zero-based index and true if found
- Return the zero value of T and false if index is negative
- Return the zero value of T and false if index is beyond the sequence bounds
- Return the zero value of T and false if the enumerator is nil
- Process elements sequentially until the specified index is reached in sorted order
Parameters:
index - the zero-based index of the element to retrieve from the sorted sequence
Returns:
The element at the specified index in sorted order and true if found, zero value of T and false otherwise
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. The operation must perform sorting and then iterate through the sorted sequence until the specified index is reached. Time complexity: O(n log n) for sorting + O(index + 1) for iteration = O(n log n) where n is the total number of elements.
⚠️ Memory note: This operation buffers all elements in memory during sorting, but does not buffer elements beyond the specified index during iteration. Space complexity: O(n) - allocates memory for all elements during sorting.
Notes:
- Index must be non-negative (negative indices return zero value and false)
- If index is beyond sequence bounds, returns zero value and false
- If enumerator is nil, returns zero value and false
- Actual sorting computation occurs only during this first operation
- Processes elements sequentially in sorted order - early termination when index is found
- Custom comparer functions are used for element comparison during sorting
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- No elements are buffered beyond the target index - memory efficient for early indices
- This is a terminal operation that materializes the enumeration
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
- Supports complex types including structs with non-comparable fields
func (OrderEnumeratorAny[T]) FirstOrDefault ¶ added in v1.25.7
func (o OrderEnumeratorAny[T]) FirstOrDefault(defaultValue T) T
FirstOrDefault returns the first element of a sorted enumeration in sorted order, or a default value if the enumeration is empty or nil. This method supports any type T, including non-comparable types with custom sorting logic.
The first or default operation will:
- Execute deferred sorting rules to determine the sorted order
- Return the first element from the enumeration in sorted order if it exists
- Return the provided default value if the enumeration is empty or nil
- Stop enumeration immediately after finding the first element
- Handle nil enumerators gracefully
Parameters:
defaultValue - the value to return if the enumeration is empty or nil
Returns:
The first element of the enumeration in sorted order, or the default value if enumeration is empty
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. The operation must perform sorting to determine the first element in sorted order. Time complexity: O(n log n) for sorting where n is the total number of elements.
⚠️ Memory note: This operation buffers all elements in memory during sorting. Space complexity: O(n) - allocates memory for all elements during sorting.
Notes:
- If the enumerator is nil, returns the defaultValue
- If the enumeration is empty, returns the defaultValue
- Actual sorting computation occurs only during this first operation
- Lazy evaluation stops immediately after finding the first element in sorted order
- This is a terminal operation that materializes the enumeration
- Custom comparer functions are used for element comparison during sorting
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- No elements are buffered beyond the first element - memory efficient after sorting
- Unlike FirstOrNil(), this method returns the value directly, not a pointer
- Safe for all types including those with zero values like 0, "", false, etc.
- For sorted enumerations, this typically returns the minimum element according to sorting rules
- When using zero value as default, consider using FirstOrNil() for distinction
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
- Supports complex types including structs with non-comparable fields
func (OrderEnumeratorAny[T]) FirstOrNil ¶ added in v1.25.7
func (o OrderEnumeratorAny[T]) FirstOrNil() *T
FirstOrNil returns a pointer to the first element of a sorted enumeration. with the ability to distinguish between "no elements" and "zero value" cases. This method supports any type T, including non-comparable types with custom sorting logic.
The first operation will:
- Execute deferred sorting rules to determine the sorted order
- Return a pointer to the first element in sorted order if the enumeration contains elements
- Return nil if the enumeration is empty or nil
- Stop enumeration immediately after finding the first element
- Handle nil enumerators gracefully
Returns:
A pointer to the first element in sorted order, or nil if enumeration is empty or nil
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. The operation must perform sorting to determine the first element in sorted order. Time complexity: O(n log n) for sorting where n is the total number of elements.
⚠️ Memory note: This operation buffers all elements in memory during sorting. Space complexity: O(n) - allocates memory for all elements during sorting.
Notes:
- If the enumerator is nil, returns nil
- If the enumeration is empty, returns nil
- Actual sorting computation occurs only during this first operation
- Lazy evaluation stops immediately after finding the first element in sorted order
- This is a terminal operation that materializes the enumeration
- Custom comparer functions are used for element comparison during sorting
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- No elements are buffered beyond the first element - memory efficient after sorting
- Returns pointer to allow distinction between "no elements" (nil) and "zero value" element
- Safe for all types including those with zero values like 0, "", false, etc.
- For sorted enumerations, this typically returns the minimum element according to sorting rules
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
- Supports complex types including structs with non-comparable fields
func (OrderEnumeratorAny[T]) LastOrDefault ¶ added in v1.25.7
func (o OrderEnumeratorAny[T]) LastOrDefault(defaultValue T) T
LastOrDefault returns the last element of a sorted enumeration in sorted order, or a default value if the enumeration is empty or nil. This method supports any type T, including non-comparable types with custom sorting logic.
The last or default operation will:
- Execute deferred sorting rules to determine the sorted order
- Iterate through all elements in the sorted enumeration
- Keep track of the most recent element encountered in sorted order
- Return the last element if enumeration contains elements
- Return the provided default value if the enumeration is empty or nil
- Handle nil enumerators gracefully
Parameters:
defaultValue - the value to return if the enumeration is empty or nil
Returns:
The last element of the enumeration in sorted order, or the default value if enumeration is empty
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation and must iterate through the entire sorted enumeration to find the last element. Time complexity: O(n log n) for sorting + O(n) for iteration = O(n log n) where n is the number of elements. For large enumerations, this may be expensive.
⚠️ Memory note: This operation buffers all elements in memory during sorting, but does not buffer elements beyond tracking the last element during iteration. Space complexity: O(n) - allocates memory for all elements during sorting.
Notes:
- If the enumerator is nil, returns the defaultValue
- If the enumeration is empty, returns the defaultValue
- Actual sorting computation occurs only during this first operation
- Custom comparer functions are used for element comparison during sorting
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Time complexity: O(n log n) where n is the number of elements
- Space complexity: O(n) during sorting, O(1) during iteration
- Unlike LastOrNil(), this method returns the value directly, not a pointer
- Safe for all types including those with zero values like 0, "", false, etc.
- For sorted enumerations, this typically returns the maximum element according to sorting rules
- When using zero value as default, consider using LastOrNil() for distinction
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
- Supports complex types including structs with non-comparable fields
func (OrderEnumeratorAny[T]) LastOrNil ¶ added in v1.25.7
func (o OrderEnumeratorAny[T]) LastOrNil() *T
LastOrNil returns a pointer to the last element of a sorted enumeration in sorted order, or nil if the enumeration is empty or nil. This method supports any type T, including non-comparable types with custom sorting logic.
The last or nil operation will:
- Execute deferred sorting rules to determine the sorted order
- Iterate through all elements in the sorted enumeration
- Keep track of the most recent element encountered in sorted order
- Return a pointer to the last element if enumeration contains elements
- Return nil if the enumeration is empty or nil
- Handle nil enumerators gracefully
Returns:
A pointer to the last element in sorted order, or nil if enumeration is empty or nil
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation and must iterate through the entire sorted enumeration to find the last element. Time complexity: O(n log n) for sorting + O(n) for iteration = O(n log n) where n is the number of elements. For large enumerations, this may be expensive.
⚠️ Memory note: This operation buffers all elements in memory during sorting, but does not buffer elements beyond tracking the last element during iteration. Space complexity: O(n) - allocates memory for all elements during sorting.
Notes:
- If the enumerator is nil, returns nil
- If the enumeration is empty, returns nil
- Actual sorting computation occurs only during this first operation
- Custom comparer functions are used for element comparison during sorting
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Time complexity: O(n log n) where n is the number of elements
- Space complexity: O(n) during sorting, O(1) during iteration
- Returns pointer to allow distinction between "no elements" (nil) and "zero value" element
- Safe for all types including those with zero values like 0, "", false, etc.
- For sorted enumerations, this typically returns the maximum element according to sorting rules
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
- Supports complex types including structs with non-comparable fields
func (OrderEnumeratorAny[T]) SingleBy ¶ added in v1.25.7
func (o OrderEnumeratorAny[T]) SingleBy(comparer comparer.EqualityComparer[T]) (T, error)
SingleBy returns the single element of a sorted sequence that satisfies the provided equality comparer. This operation is useful when you expect exactly one element in the sorted sequence and need custom equality logic. This method supports any type T, including non-comparable types with custom equality logic.
The SingleBy operation will:
- Execute deferred sorting rules to determine the sorted order
- Return the single element if the sequence contains exactly one distinct element according to the comparer
- Return an error if the sequence is empty ("sequence contains no elements")
- Return an error if the sequence contains more than one distinct element according to the comparer
- Process elements sequentially until completion or second distinct element found
- Handle nil enumerators gracefully
Parameters:
comparer - an EqualityComparer that defines when two elements are considered equal
Returns:
The single element of the sequence and nil error if successful, zero value of T and error otherwise
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation and must iterate through the sequence until completion or second distinct element found. For large sequences with multiple distinct elements, this may process more elements than necessary. Time complexity: O(n log n) for sorting + O(n) for validation = O(n log n) where n is the number of elements processed.
⚠️ Memory note: This operation buffers all elements in memory during sorting, and buffers elements to perform equality comparison using hash-based lookup. Memory usage depends on the number of distinct elements encountered during processing. Space complexity: O(n) - allocates memory for all elements during sorting and comparison.
Notes:
- If the enumerator is nil, returns zero value and error ("sequence contains no elements")
- If the enumeration is empty, returns zero value and error ("sequence contains no elements")
- If the enumeration contains more than one distinct element, returns zero value and error ("sequence contains more than one element")
- Actual sorting computation occurs only during this first operation
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Uses the provided comparer's Equals and GetHashCode methods for efficient element comparison
- Elements are buffered in hash buckets during comparison for efficient duplicate detection
- This is a terminal operation that materializes the enumeration
- Works with any type T (including non-comparable types) when used with appropriate comparer
- The comparer functions must be consistent and deterministic
- For large enumerations, processing stops early when second distinct element is found
- This method should be used when you are certain the sequence contains exactly one distinct element
- Common use cases include lookup by custom equality logic, complex object comparison, or unique constraint validation
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
- Supports complex types including structs with non-comparable fields
func (OrderEnumeratorAny[T]) Skip ¶ added in v1.25.7
func (o OrderEnumeratorAny[T]) Skip(n int) EnumeratorAny[T]
Skip bypasses a specified number of elements in a sorted enumeration and then yields the remaining elements in sorted order. This operation is useful for pagination, skipping headers, or bypassing initial elements in the context of sorted sequences. This method supports any type T, including non-comparable types with custom sorting logic.
The skip operation will:
- Execute deferred sorting rules to determine the sorted order
- Bypass the first n elements from the sorted enumeration
- Yield all remaining elements in sorted order
- Handle edge cases gracefully (n <= 0, n >= count)
- Support early termination when consumer returns false
Parameters:
n - the number of elements to skip (must be non-negative)
Returns:
An EnumeratorAny[T] that yields elements in sorted order after skipping the first n elements
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. Time complexity: O(n log n) for sorting where n is the total number of elements. The skip operation itself is O(1) - elements are skipped during iteration. For large enumerations, this may process more elements than necessary.
⚠️ Memory note: This operation buffers all elements in memory during sorting. Space complexity: O(n) - allocates memory for all elements during sorting. No additional buffering beyond sorting phase.
Notes:
- If n <= 0, returns an enumerator that yields all elements in sorted order
- If n >= total number of elements, returns an empty enumerator
- If the original enumerator is nil, returns an empty enumerator (not nil)
- Actual sorting computation occurs only during first enumeration
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Lazy evaluation - elements are processed and skipped during iteration
- No elements are buffered beyond sorting phase - memory efficient after sorting
- Negative values of n are treated as 0
- The enumeration is consumed sequentially, so skipped elements are still processed during sorting
- Elements are yielded in sorted order according to all accumulated sorting rules
- Subsequent enumerations will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
- Supports complex types including structs with non-comparable fields
func (OrderEnumeratorAny[T]) SkipLast ¶ added in v1.25.7
func (o OrderEnumeratorAny[T]) SkipLast(n int) EnumeratorAny[T]
SkipLast bypasses a specified number of elements at the end of a sorted enumeration and yields the remaining elements in sorted order. This operation is useful for removing trailing elements like footers, summaries, or fixed-size endings from sorted sequences. This method supports any type T, including non-comparable types with custom sorting logic.
The skip last operation will:
- Execute deferred sorting rules to determine the sorted order
- Buffer elements to track which are the final n elements in sorted order
- Yield elements only after confirming they are not among the last n in sorted order
- Handle edge cases gracefully (n <= 0, n >= count)
- Support early termination when consumer returns false
Parameters:
n - the number of elements to skip from the end (must be non-negative)
Returns:
An EnumeratorAny[T] that yields elements in sorted order except the last n elements
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. This operation buffers up to n elements in memory using a circular buffer for efficient memory usage. Time complexity: O(n log n) for sorting where n is the total number of elements. For large values of n, this may consume significant memory.
⚠️ Evaluation note: This operation is partially lazy - elements are processed as the enumeration proceeds, but the last n elements are buffered and never yielded. The enumeration must progress beyond n elements to yield earlier ones. Actual sorting computation occurs only during enumeration.
⚠️ Memory note: This operation buffers all elements in memory during sorting, plus additional buffering of up to n elements for the skip operation. Space complexity: O(m + n) where m is total elements and n is skip count.
Notes:
- If n <= 0, returns an enumerator that yields all elements in sorted order
- If n >= total number of elements, returns an empty enumerator
- If the original enumerator is nil, returns an empty enumerator
- Elements are yielded in sorted order according to all accumulated sorting rules
- Actual sorting computation occurs only during first enumeration
- Custom comparer functions are used for element comparison during sorting
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Subsequent enumerations will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
- Supports complex types including structs with non-comparable fields
func (OrderEnumeratorAny[T]) SkipWhile ¶ added in v1.25.7
func (o OrderEnumeratorAny[T]) SkipWhile(predicate func(T) bool) EnumeratorAny[T]
SkipWhile bypasses elements in a sorted enumeration as long as a specified condition is true and then yields the remaining elements in sorted order. This operation is useful for skipping elements until a certain condition is met in the context of sorted sequences. This method supports any type T, including non-comparable types.
The skip while operation will:
- Execute deferred sorting rules to determine the sorted order
- Bypass elements from the beginning while the predicate returns true
- Once the predicate returns false for an element, yield that element and all subsequent elements
- Support early termination when consumer returns false
Parameters:
predicate - a function that determines whether to skip an element
Returns:
An EnumeratorAny[T] that yields elements in sorted order after skipping initial elements that match the condition
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. Time complexity: O(n log n) for sorting where n is the total number of elements. The predicate is evaluated during iteration after sorting is complete.
⚠️ Memory note: This operation buffers all elements in memory during sorting. Space complexity: O(n) - allocates memory for all elements during sorting. No additional buffering beyond sorting phase.
Notes:
- If the predicate never returns false, returns an empty enumerator
- If the predicate immediately returns false for the first element, returns all elements in sorted order
- If the original enumerator is nil, returns an empty enumerator
- Actual sorting computation occurs only during first enumeration
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Lazy evaluation - elements are processed and evaluated during iteration
- The enumeration stops skipping as soon as the first non-matching element is found
- Once skipping stops, all remaining elements are yielded (even if they would match the predicate)
- Elements are yielded in sorted order according to all accumulated sorting rules
- Subsequent enumerations will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
- Supports complex types including structs with non-comparable fields
func (OrderEnumeratorAny[T]) Take ¶ added in v1.25.7
func (o OrderEnumeratorAny[T]) Take(n int) EnumeratorAny[T]
Take returns a specified number of contiguous elements from the start of a sorted enumeration in sorted order. This operation is useful for pagination, limiting results, or taking samples from sorted sequences. This method supports any type T, including non-comparable types with custom sorting logic.
The take operation will:
- Execute deferred sorting rules to determine the sorted order
- Yield the first n elements from the sorted enumeration
- Stop enumeration once n elements have been yielded
- Handle edge cases gracefully (n <= 0, n >= count)
- Support early termination when consumer returns false
Parameters:
n - the number of elements to take (must be non-negative)
Returns:
An EnumeratorAny[T] that yields at most n elements from the start in sorted order
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. Time complexity: O(n log n) for sorting where n is the total number of elements. The take operation itself is O(1) - elements are taken during iteration. For large enumerations where n << total, this may process more elements than necessary.
⚠️ Memory note: This operation buffers all elements in memory during sorting. Space complexity: O(n) - allocates memory for all elements during sorting. No additional buffering beyond sorting phase.
Notes:
- If n <= 0, returns an empty enumerator
- If n >= total number of elements, returns all available elements in sorted order
- If the original enumerator is nil, returns an empty enumerator
- Actual sorting computation occurs only during first enumeration
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Lazy evaluation - elements are processed and yielded during iteration
- No elements are buffered beyond sorting phase - memory efficient after sorting
- Negative values of n are treated as 0
- Early termination by the consumer stops further enumeration
- The enumeration stops as soon as n elements are yielded or the source is exhausted
- Elements are yielded in sorted order according to all accumulated sorting rules
- Subsequent enumerations will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
- Supports complex types including structs with non-comparable fields
func (OrderEnumeratorAny[T]) TakeLast ¶ added in v1.25.7
func (o OrderEnumeratorAny[T]) TakeLast(n int) EnumeratorAny[T]
TakeLast returns a specified number of contiguous elements from the end of a sorted enumeration in sorted order. This operation is useful for getting the final elements, such as last N records, trailing averages, or end-of-sequence markers from sorted sequences. This method supports any type T, including non-comparable types with custom sorting logic.
The take last operation will:
- Execute deferred sorting rules to determine the sorted order
- Buffer elements to track the last n elements seen so far in sorted order
- Yield the final n elements when enumeration completes
- Handle edge cases gracefully (n <= 0, n >= count)
- Support early termination when consumer returns false
Parameters:
n - the number of elements to take from the end (must be non-negative)
Returns:
An EnumeratorAny[T] that yields the last n elements in sorted order
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. This operation buffers up to n elements in memory to track which elements should be yielded. Time complexity: O(n log n) for sorting where n is the total number of elements. For large values of n, this may consume significant memory. All elements must be processed before any are yielded.
⚠️ Evaluation note: This operation is not lazy in the traditional sense - the entire source enumeration must be consumed and sorted before yielding begins. Elements are yielded in sorted order according to all accumulated sorting rules.
⚠️ Memory note: This operation buffers all elements in memory during sorting, plus additional buffering of up to n elements for the take operation. Space complexity: O(m + n) where m is total elements and n is take count.
Notes:
- If n <= 0, returns an empty enumerator
- If n >= total number of elements, returns all available elements in sorted order
- If the original enumerator is nil, returns an empty enumerator
- Actual sorting computation occurs only during first enumeration
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Negative values of n are treated as 0
- The enumeration stops as soon as the consumer returns false
- Elements are yielded in sorted order according to all accumulated sorting rules
- Subsequent enumerations will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
- Supports complex types including structs with non-comparable fields
func (OrderEnumeratorAny[T]) TakeWhile ¶ added in v1.25.7
func (o OrderEnumeratorAny[T]) TakeWhile(predicate func(T) bool) EnumeratorAny[T]
TakeWhile returns elements from a sorted enumeration as long as a specified condition is true. This operation is useful for taking elements until a certain condition is met, such as taking elements while they are valid or within a range, in the context of sorted sequences. This method supports any type T, including non-comparable types with custom sorting logic.
The take while operation will:
- Execute deferred sorting rules to determine the sorted order
- Yield elements from the start while the predicate returns true
- Stop enumeration as soon as the predicate returns false for an element
- Handle edge cases gracefully (nil enumerator, always false predicate)
- Support early termination when consumer returns false
Parameters:
predicate - a function that determines whether to take an element
Returns:
An EnumeratorAny[T] that yields elements in sorted order while the condition is true
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. Time complexity: O(n log n) for sorting where n is the total number of elements. The predicate evaluation is O(1) per element during iteration. For large enumerations, this may process more elements than necessary.
⚠️ Memory note: This operation buffers all elements in memory during sorting. Space complexity: O(n) - allocates memory for all elements during sorting. No additional buffering beyond sorting phase.
Notes:
- If the predicate immediately returns false for the first element, returns empty enumerator
- If the predicate never returns false, returns all elements from the sorted enumeration
- If the original enumerator is nil, returns an empty enumerator
- Actual sorting computation occurs only during first enumeration
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Lazy evaluation - elements are processed and evaluated during iteration
- No elements are buffered beyond sorting phase - memory efficient after sorting
- The enumeration stops as soon as the predicate returns false or consumer returns false
- Once the predicate returns false for any element, no subsequent elements are evaluated
- Elements are yielded in sorted order according to all accumulated sorting rules
- Subsequent enumerations will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
- Supports complex types including structs with non-comparable fields
func (OrderEnumeratorAny[T]) ThenBy ¶ added in v1.25.7
func (o OrderEnumeratorAny[T]) ThenBy(comparer comparer.ComparerFunc[T]) OrderEnumeratorAny[T]
ThenBy performs a subsequent ordering of the elements in ascending order according to a comparer function. This method adds a secondary (or further) sorting level to an existing ordered sequence for any type T.
The ThenBy operation:
- Accumulates additional sorting rules without immediate execution (lazy evaluation)
- Returns an OrderEnumeratorAny that supports further chaining with additional ThenBy operations
- Uses the provided comparer function to determine secondary element ordering
- Maintains stable sorting (equal elements preserve relative order)
- Works with any type T, including non-comparable types
Parameters:
comparer - a ComparerFunc that defines the secondary sort order by comparing two elements of type T
The function should return:
< 0 if first element is less than second
= 0 if elements are equal
> 0 if first element is greater than second
Returns:
An OrderEnumeratorAny[T] that contains elements sorted by both primary and secondary criteria
⚠️ Performance note: This is a deferred execution operation that accumulates sorting rules. Actual sorting computation occurs during first enumeration. Time complexity: O(1) for rule accumulation, O(n log n) for actual sorting during enumeration with all accumulated rules.
Notes:
- This is a lazy operation - no sorting occurs until enumeration begins
- Can be chained multiple times to create multiple sorting levels
- Each ThenBy adds a new sorting level with lower priority than previous levels
- Custom comparer functions must handle all possible input values, including nil
- The comparer function must be deterministic and consistent
- Works with any type T, including complex structs with non-comparable fields
- Thread-safe for rule accumulation, but enumeration should be single-threaded
func (OrderEnumeratorAny[T]) ThenByDescending ¶ added in v1.25.7
func (o OrderEnumeratorAny[T]) ThenByDescending(comparer comparer.ComparerFunc[T]) OrderEnumeratorAny[T]
ThenByDescending performs a subsequent ordering of the elements in descending order according to a comparer function. This method adds a secondary (or further) sorting level to an existing ordered sequence for any type T.
The ThenByDescending operation:
- Accumulates additional sorting rules without immediate execution (lazy evaluation)
- Returns an OrderEnumeratorAny that supports further chaining with additional ThenBy operations
- Uses the provided comparer function to determine secondary element ordering (reversed)
- Maintains stable sorting (equal elements preserve relative order)
- Works with any type T, including non-comparable types
Parameters:
comparer - a ComparerFunc that defines the secondary sort order by comparing two elements of type T
The function should return:
< 0 if first element is less than second
= 0 if elements are equal
> 0 if first element is greater than second
Note: The final order for this level will be reversed (descending)
Returns:
An OrderEnumeratorAny[T] that contains elements sorted by both primary and secondary criteria
⚠️ Performance note: This is a deferred execution operation that accumulates sorting rules. Actual sorting computation occurs during first enumeration. Time complexity: O(1) for rule accumulation, O(n log n) for actual sorting during enumeration with all accumulated rules.
Notes:
- This is a lazy operation - no sorting occurs until enumeration begins
- Can be chained multiple times to create multiple sorting levels
- Each ThenByDescending adds a new sorting level with lower priority than previous levels
- Custom comparer functions must handle all possible input values, including nil
- The comparer function must be deterministic and consistent
- Works with any type T, including complex structs with non-comparable fields
- Thread-safe for rule accumulation, but enumeration should be single-threaded
func (OrderEnumeratorAny[T]) ToBatch ¶ added in v1.25.8
func (e OrderEnumeratorAny[T]) ToBatch(batchSize int) [][]T
ToBatch groups elements from a sorted enumeration into batches of specified size and returns them as a slice of slices in sorted order. This operation is useful for processing large sorted sequences in chunks, implementing pagination, or optimizing batch operations on sorted data. This method supports any type T, including non-comparable types with custom sorting logic.
The to batch operation will:
- Execute deferred sorting rules to determine the sorted order
- Group consecutive elements in sorted order into slices of at most batchSize elements
- Return all batches as a slice when enumeration is complete
- Handle edge cases gracefully (batchSize <= 0, empty source)
- Materialize the entire sorted enumeration (terminal operation)
Parameters:
batchSize - the maximum number of elements per batch (must be positive)
Returns:
A slice containing batches of elements in sorted order, or empty slice if no batches
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation and must iterate through the entire sorted enumeration to create all batches. Time complexity: O(n log n) for sorting + O(n) for batching = O(n log n) where n is the number of elements.
⚠️ Memory note: This operation buffers all elements in memory during sorting, plus additional buffering for batching. Space complexity: O(n) where n is total elements.
⚠️ Evaluation note: This operation is not lazy in the traditional sense - actual sorting computation occurs immediately upon calling this method. All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting.
Notes:
- If batchSize <= 0, returns empty slice
- If the original enumerator is nil, returns empty slice
- Last batch may contain fewer elements than batchSize
- Terminal operation - consumes entire sorted enumeration
- Each batch is a separate slice - safe for modification
- No elements are lost - all elements from source are included in batches
- Actual sorting computation occurs only during this operation
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- Elements are grouped in sorted order according to all accumulated sorting rules
- Subsequent calls will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
- Supports complex types including structs with non-comparable fields
- Custom comparer functions are used for element comparison during sorting
func (OrderEnumeratorAny[T]) ToChannel ¶ added in v1.25.7
func (o OrderEnumeratorAny[T]) ToChannel(bufferSize int) <-chan T
ToChannel converts a sorted enumeration to a channel that yields all elements in sorted order. This operation is useful for converting lazy sorted enumerations into channel-based processing pipelines or for interoperability with goroutines. This method supports any type T, including non-comparable types with custom sorting logic.
The to channel operation will:
- Execute deferred sorting rules to determine the sorted order
- Create a new channel with specified buffer size
- Start a goroutine that iterates through the sorted enumeration
- Send each element to the channel in sorted order
- Close the channel when enumeration is complete
- Handle nil enumerators gracefully
Parameters:
bufferSize - the buffer size for the returned channel (0 for unbuffered)
Returns:
A read-only channel containing all elements from the enumeration in sorted order
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. Time complexity: O(n log n) for sorting where n is the total number of elements. The channel creation and goroutine startup is O(1). For large enumerations, this may process more elements than necessary.
⚠️ Memory note: This operation buffers all elements in memory during sorting. Space complexity: O(n) - allocates memory for all elements during sorting. Plus O(bufferSize) for the channel buffer.
⚠️ Resource management: This operation starts a goroutine that runs until the enumeration is complete. Always consume all elements or the goroutine may block indefinitely.
⚠️ Blocking behavior: The goroutine will block when trying to send to a full channel if there's no reader. Use appropriate buffer size.
⚠️ Warning: If the returned channel is not fully consumed, the goroutine may leak. Always range over the entire channel or ensure proper cleanup.
Notes:
- If the enumerator is nil, returns a closed channel
- If the enumeration is empty, returns an empty but closed channel
- Actual sorting computation occurs only during first enumeration
- All accumulated sorting rules (OrderBy + ThenBy levels) are applied during sorting
- The goroutine automatically closes the channel when done
- Time complexity: O(n log n) where n is the number of elements
- Space complexity: O(n + bufferSize) for sorting plus channel buffering
- The enumeration runs in a separate goroutine, enabling concurrent processing
- Elements are yielded in sorted order according to all accumulated sorting rules
- Subsequent enumerations will re-execute sorting (sorting is not cached)
- Stable sorting preserves relative order of equal elements according to sorting rules
- Supports complex types including structs with non-comparable fields
func (OrderEnumeratorAny[T]) ToSlice ¶ added in v1.25.7
func (o OrderEnumeratorAny[T]) ToSlice() []T
ToSlice converts an ordered enumeration to a slice containing all elements in sorted order. This operation is useful for materializing lazy ordered enumerations into concrete sorted collections. This method supports any type T, including non-comparable types with custom sorting logic.
The to slice operation will:
- Execute deferred sorting rules and iterate through all elements in sorted order
- Collect all elements into a new slice preserving the sorted order
- Return the slice containing all elements in their sorted positions
- Handle nil enumerators gracefully
Returns:
A slice containing all elements from the enumeration in sorted order, or empty slice if enumerator is nil
⚠️ Performance note: This is a terminal operation that triggers actual sorting computation. The operation must iterate through the entire enumeration and perform sorting. Time complexity: O(n log n) for sorting + O(n) for collection = O(n log n). For large enumerations, this may be expensive in both time and memory.
⚠️ Memory note: This operation buffers all elements in memory during sorting and collection. Space complexity: O(n) - allocates memory for all elements plus temporary sorting storage.
Notes:
- If the enumerator is nil, returns an empty slice (not nil)
- If the enumeration is empty, returns an empty slice
- Sorting is performed according to all accumulated sorting rules (OrderBy + ThenBy levels)
- Custom comparer functions are used for element comparison during sorting
- The returned slice preserves the fully sorted order of elements
- Actual sorting computation occurs only during this first materialization
- Subsequent calls will re-execute sorting (sorting is not cached)
- Use with caution for infinite or very large enumerations
- Stable sorting preserves relative order of equal elements according to sorting rules
- Supports complex types including structs with non-comparable fields
Source Files
¶
- all.go
- any.go
- average.go
- concat.go
- contains.go
- count.go
- default_if_empty.go
- distinct.go
- element_at.go
- empty.go
- enumerator.go
- except.go
- first_or_default.go
- first_or_nil.go
- foreach.go
- from_channel.go
- from_slice.go
- hash_set.go
- infrastructure.go
- intersect.go
- last_or_default.go
- last_or_nil.go
- long_count.go
- max_bool.go
- max_by.go
- max_byte.go
- max_float.go
- max_int.go
- max_rune.go
- max_string.go
- max_time.go
- min_bool.go
- min_by.go
- min_byte.go
- min_float.go
- min_int.go
- min_rune.go
- min_string.go
- min_time.go
- order_by.go
- order_enumerator.go
- range.go
- repeat.go
- single.go
- single_by.go
- skip.go
- skip_last.go
- skip_while.go
- sum_float.go
- sum_int.go
- take.go
- take_last.go
- take_while.go
- then_by.go
- to_batch.go
- to_channel.go
- to_map.go
- to_slice.go
- union.go
- where.go