> # The C# `Sequence` Interface

> The `Sequence` interface is used to store an array field in the database as a `sequence`.

> ### For an overview see page C# Classes

> ## Class Definition

>         public class Sequence : IDisposable
>             // ===== CONSTANTS =====
>             public const int TileSize = 100;
>             public const ulong Infinity = ulong.MaxValue;

>             // ===== PROPERTIES =====
>             public Array TileItems { get; }
>             public ulong FirstPosition { get; }
>             public ulong LastPosition { get; }
>             public ulong NextPosition { get; }
>             public Type ElementType { get; }
>             public int ElementSize { get; }

>             // ===== CONSTRUCTORS (internal) =====
>             internal Sequence(IDatabaseWrapper impl, IntPtr hnd);

>             // ===== TILE & NAVIGATION METHODS =====
>             public bool NextTile();
>             public int ItemRepeatCount(int i);
>             public Sequence RLEDecode();
>             public static bool IsRLE(Connection con);

>             // ===== ELEMENT ACCESS METHODS =====
>             public int Get(Array buffer);
>             public bool Next(out byte val);
>             public bool Next(out ushort val);
>             public bool Next(out uint val);
>             public bool Next(out ulong val);
>             public bool Next(out sbyte val);
>             public bool Next(out short val);
>             public bool Next(out int val);
>             public bool Next(out long val);
>             public bool Next(out float val);
>             public bool Next(out double val);
>             public bool Next(byte[] val);
>             public bool Next(out DateTime val);
>             public object Next();

>             // ===== SEQUENCE TRANSFORMATION METHODS =====
>             public Sequence Abs();
>             public Sequence Match(string pattern);
>             public Sequence Reverse();
>             public Sequence Diff();
>             public Sequence Trend();
>             public Sequence Normalize();
>             public Sequence Unique();
>             public Sequence Cast(Type elemType);
>             public Sequence Hash();
>             public Sequence Hash(Sequence other);
>             public Sequence Repeat(int count);
>             public Sequence Thin(ulong origin, ulong step);
>             public Sequence Subseq(ulong from, ulong till);
>             public Sequence Map(Sequence positions);
>             public Sequence Filter(Sequence cond);
>             public Sequence FilterPos();
>             public Sequence If(Sequence then, Sequence otherwise, bool lazy);

>             // ===== SEQUENCE COMBINATION METHODS =====
>             public static Sequence Concat(Sequence left, Sequence right);
>             public static Sequence Cat(Sequence left, Sequence right);
>             public Sequence Wsum(Sequence weights);
>             public Sequence Wavg(Sequence weights);
>             public static Sequence Cov(Sequence left, Sequence right);
>             public static Sequence Corr(Sequence left, Sequence right);
>             public Sequence stretch(Sequence ts1, Sequence ts2, object filler);
>             public Sequence Stretch0(Sequence ts1, Sequence ts2, object filler);
>             public Sequence AsofJoin(Sequence ts1, Sequence ts2);

>             // ===== AGGREGATION METHODS (global) =====
>             public Sequence AggCount();
>             public Sequence AggMax();
>             public Sequence AggMin();
>             public Sequence AggSum();
>             public Sequence AggPrd();
>             public Sequence AggAvg();
>             public Sequence AggVar();
>             public Sequence AggDev();
>             public Sequence AggVarSamp();
>             public Sequence AggDevSamp();
>             public Sequence aggApproxDC();
>             public Sequence aggApproxHashDC();
>             public Sequence AggMinMax();

>             // ===== GROUPED AGGREGATION METHODS =====
>             public Sequence GroupAggWavg(Sequence weight, Sequence groupBy);
>             public Sequence GroupAggMax(Sequence groupBy);
>             public Sequence GroupAggMin(Sequence groupBy);
>             public Sequence GroupAggSum(Sequence groupBy);
>             public Sequence GroupAggAvg(Sequence groupBy);
>             public Sequence GroupAggVar(Sequence groupBy);
>             public Sequence GroupAggDev(Sequence groupBy);
>             public Sequence GroupAggVarSamp(Sequence groupBy);
>             public Sequence GroupAggDevSamp(Sequence groupBy);
>             public Sequence GroupAggFirst(Sequence groupBy);
>             public Sequence GroupAggLast(Sequence groupBy);
>             public Sequence GroupAggCount();
>             public Sequence GroupAggApproxDC(Sequence groupBy);
>             public Sequence GroupAggApproxHashDC(Sequence groupBy);

>             // ===== HASH-BASED AGGREGATION METHODS =====
>             public Sequence HashAggMax(out Sequence groups, Sequence groupBy, int nGroups);
>             public Sequence HashAggMin(out Sequence groups, Sequence groupBy, int nGroups);
>             public Sequence HashAggSum(out Sequence groups, Sequence groupBy, int nGroups);
>             public Sequence HashAggAvg(out Sequence groups, Sequence groupBy, int nGroups);
>             public Sequence HashAggCount(out Sequence groups, int nGroups);
>             public Sequence HashAggApproxdc(out Sequence groups, Sequence groupBy, int nGroups);
>             public Sequence HashAggDistinctCount(out Sequence groups, Sequence groupBy, int nGroups, int nPairs);
>             public Sequence HashAggDupCount(out Sequence groups, Sequence groupBy, int nGroups, int nPairs, int minOccurrences);

>             // ===== GRID-BASED AGGREGATION METHODS =====
>             public Sequence GridAggMax(int interval);
>             public Sequence GridAggMin(int interval);
>             public Sequence GridAggSum(int interval);
>             public Sequence GridAggAvg(int interval);
>             public Sequence GridAggVar(int interval);
>             public Sequence GridAggDev(int interval);
>             public Sequence GridAggVarSamp(int interval);
>             public Sequence GridAggDevSamp(int interval);

>             // ===== WINDOW-BASED AGGREGATION METHODS =====
>             public Sequence WindowAggMax(int interval);
>             public Sequence WindowAggMin(int interval);
>             public Sequence WindowAggSum(int interval);
>             public Sequence WindowAggAvg(int interval);
>             public Sequence WindowAggVar(int interval);
>             public Sequence WindowAggDev(int interval);
>             public Sequence WindowAggVarSamp(int interval);
>             public Sequence WindowAggDevSamp(int interval);
>             public Sequence WindowAggEma(int period);
>             public Sequence WindowAggAtr(int period);

>             // ===== CUMULATIVE AGGREGATION METHODS =====
>             public Sequence CumAggMax();
>             public Sequence CumAggMin();
>             public Sequence CumAggSum();
>             public Sequence CumAggPrd();
>             public Sequence CumAggAvg();
>             public Sequence CumAggVar();
>             public Sequence CumAggDev();
>             public Sequence CumAggVarSamp();
>             public Sequence CumAggDevSamp();

>             // ===== TOP-N & ANALYTICAL METHODS =====
>             public Sequence TopMax(int top);
>             public Sequence TopMin(int top);
>             public Sequence TopPosMax(int top);
>             public Sequence TopPosMin(int top);
>             public Sequence Histogram(object low, object high, int nIntervals);
>             public Sequence Cross(int firstCrossDirection);
>             public Sequence Extrema(int firstExtremum);
>             public ulong[] Sort(Array arr, SequenceOrder order);

>             // ===== SEQUENCE FACTORY METHODS =====
>             public static Sequence Parse(Connection con, String val, Type elemType);
>             public static Sequence Constant(Connection con, double val);
>             public static Sequence Constant(Connection con, float val);
>             public static Sequence Constant(Connection con, byte val);
>             public static Sequence Constant(Connection con, ushort val);
>             public static Sequence Constant(Connection con, uint val);
>             public static Sequence Constant(Connection con, ulong val);
>             public static Sequence Constant(Connection con, sbyte val);
>             public static Sequence Constant(Connection con, short val);
>             public static Sequence Constant(Connection con, int val);
>             public static Sequence Constant(Connection con, long val);
>             public static Sequence Constant(Connection con, byte[] val);

>             // ===== ARITHMETIC OPERATORS =====
>             public static Sequence operator +(Sequence left, Sequence right);
>             public static Sequence operator -(Sequence left, Sequence right);
>             public static Sequence operator *(Sequence left, Sequence right);
>             public static Sequence operator /(Sequence left, Sequence right);
>             public static Sequence operator %(Sequence left, Sequence right);
>             public static Sequence operator -(Sequence seq);

>             // ===== COMPARISON OPERATORS =====
>             public static Sequence operator ==(Sequence left, Sequence right);
>             public static Sequence operator !=(Sequence left, Sequence right);
>             public static Sequence operator <(Sequence left, Sequence right);
>             public static Sequence operator >(Sequence left, Sequence right);
>             public static Sequence operator <=(Sequence left, Sequence right);
>             public static Sequence operator >=(Sequence left, Sequence right);
>             public static Sequence Max(Sequence left, Sequence right);
>             public static Sequence Min(Sequence left, Sequence right);

>             // ===== LOGICAL OPERATORS =====
>             public static Sequence operator &(Sequence left, Sequence right);
>             public static Sequence operator |(Sequence left, Sequence right);
>             public static Sequence operator ^(Sequence left, Sequence right);
>             public static Sequence operator !(Sequence seq);

>             // ===== UTILITY & LIFECYCLE METHODS =====
>             public Sequence[] Tee();
>             public void Reset();
>             public void Close();
>             public void Dispose();
>         }

> ## Method Descriptions

> TileSize
> Constant defining the default tile size (100 items) for batch iteration through sequence elements.
> Infinity
> Constant representing an infinite position value (ulong.MaxValue), used in the `Subseq` method.
> TileItems
> Gets the array of items in the current tile. Sequences iterate in tile mode, fetching multiple items per iteration.
> FirstPosition
> Returns the position of the first element in the sequence (inclusive).
> LastPosition
> Returns the position of the last element in the sequence (inclusive).
> NextPosition
> Returns the position where the next invocation of `Next()` or `NextTile()` will place the iterator.
> ElementType
> Gets the .NET `Type` of elements stored in this sequence (e.g., int, double, string).
> ElementSize
> Gets the size in bytes of a single element in this sequence.
> ItemRepeatCount(int i)
> Returns the RLE (Run-Length Encoding) repeat count for the i-th item in the current tile. Returns 1 for non-RLE sequences.
> RLEDecode()
> Decodes an RLE-compressed sequence into a standard sequence. For non-RLE sequences, returns a copy of the iterator.
> IsRLE(Connection con)
> Static method that checks whether the underlying sequence implementation uses RLE format for the given connection.
> NextTile()
> Advances the iterator to the next tile of elements. Returns `true` if successful, `false` at end of sequence.
> Get(Array buffer)
> Extracts sequence elements into the provided array buffer. Returns the actual number of elements extracted.
> Next(out T val)
> Retrieves the next element of a specific type (byte, int, double, DateTime, etc.). Returns `true` if an element was retrieved.
> Next()
> Retrieves the next element as a generic `object`. Returns `null` if the end of sequence is reached.
> Abs()
> Returns a new sequence containing the absolute value of each element.
> Match(string pattern)
> Filters string sequence elements using an SQL LIKE-compatible pattern. Returns a boolean sequence indicating matches.
> Reverse()
> Returns a new sequence with elements in reverse order.
> Diff()
> Computes differences between consecutive pairs of elements: result[i] = input[i+1] - input[i].
> Trend()
> Calculates the trend (direction of change) for sequence elements.
> Normalize()
> Normalizes the sequence by dividing each element by the square root of the sum of squares of all elements.
> Unique()
> Removes duplicate values from a sorted sequence, keeping only distinct elements.
> Cast(Type elemType)
> Converts each element of the sequence to the specified target type.
> Hash() / Hash(Sequence other)
> Calculates a 32-bit hash code for each element. The overload combines hashes with another sequence for multi-column hashing.
> Repeat(int count)
> Repeats each element of the sequence the specified number of times: {1,2}→Repeat(3)→{1,1,1,2,2,2}.
> Thin(ulong origin, ulong step)
> Selects elements at regular intervals: starting at `origin`, every `step`-th element is included.
> Subseq(ulong from, ulong till)
> Returns an iterator through the subsequence within the inclusive range [from, till]. Use `Infinity` for unbounded end.
> Map(Sequence positions)
> Extracts elements from this sequence at positions specified by another sequence. Positions must be in ascending order.
> Filter(Sequence cond)
> Returns elements from the input sequence where the corresponding boolean condition sequence is `true`.
> FilterPos()
> Returns a sequence of positions (indices) where the input boolean sequence has `true` values.
> If(Sequence then, Sequence otherwise, bool lazy)
> Conditional selection: chooses elements from `then` or `otherwise` based on boolean values in this sequence. If `lazy=true`, unused branches are not advanced.
> Concat(Sequence left, Sequence right)
> Concatenates two sequences end-to-end: Concat({1,2}, {3,4}) → {1,2,3,4}.
> Cat(Sequence left, Sequence right)
> Concatenates corresponding elements as strings: Cat({'a','b'}, {'x','y'}) → {'ax','by'}.
> Wsum(Sequence weights) / Wavg(Sequence weights)
> Computes weighted sum or weighted average of sequence elements using the provided weights sequence.
> Cov(Sequence, Sequence) / Corr(Sequence, Sequence)
> Computes covariance or correlation coefficient between two sequences element-wise.
> stretch() / Stretch0() / AsofJoin()
> Time-series alignment methods: `stretch` repeats values to match timestamps, `Stretch0` inserts fillers for gaps, `AsofJoin` matches by closest timestamp.
> AggCount() ... AggMinMax()
> Global aggregation methods: compute count, max, min, sum, product, average, variance, standard deviation, or approximate distinct count over the entire sequence.
> GroupAgg* methods
> Grouped aggregations: compute aggregates (max, min, sum, avg, etc.) for each group defined by a grouping sequence. Requires pre-sorted input.
> HashAgg* methods
> Hash-based grouped aggregations: compute aggregates per group without requiring sorted input. Returns both aggregate results and group identifiers.
> GridAgg* methods
> Grid-based aggregations: compute aggregates over fixed-size intervals (windows) of the sequence.
> WindowAgg* methods
> Sliding window aggregations: compute aggregates over a moving window of specified size. Includes financial indicators EMA (Exponential Moving Average) and ATR (Average True Range).
> CumAgg* methods
> Cumulative aggregations: each result element is the aggregate of all preceding elements (e.g., cumulative sum, running average).
> TopMax() / TopMin() / TopPosMax() / TopPosMin()
> Returns the top N maximum/minimum values or their positions in the sequence.
> Histogram(object low, object high, int nIntervals)
> Builds a histogram by counting elements falling into equal-width bins between `low` (inclusive) and `high` (exclusive).
> Cross(int firstCrossDirection)
> Finds positions where the sequence crosses zero. Parameter controls whether to start with upward (+1), downward (-1), or any (0) crossing.
> Extrema(int firstExtremum)
> Finds positions of local minima and maxima. Parameter controls whether to start with maximum (+1), minimum (-1), or any (0).
> Sort(Array arr, SequenceOrder order)
> Sorts extracted sequence elements and returns a permutation array for reordering related data arrays.
> Parse(Connection, String, Type)
> Factory method: constructs a sequence from a string literal like "{1.0, -1.1, 0}" with specified element type.
> Constant(Connection, T val)
> Factory methods: create a sequence where every element equals the specified constant value (overloads for numeric and byte[] types).
> Arithmetic operators (+, -, *, /, %, unary -)
> Element-wise arithmetic operations between two sequences or unary negation.
> Comparison operators (==, !=, <, >, <=, >=)
> Element-wise comparisons returning a boolean sequence. Also includes static `Max()`/`Min()` for element-wise selection.
> Logical operators (&, |, ^, !)
> Element-wise logical AND, OR, XOR, and NOT operations for boolean sequences.
> Tee()
> Creates two independent iterators over the same sequence. Both must be traversed together in the same expression.
> Reset() / Close() / Dispose()
> Lifecycle methods: `Reset()` returns iterator to start; `Close()`/`Dispose()` release native resources.