AsyncQuery

Namespace: SnowBank.Linq · class

Provides a set of static methods for querying objects that implement IAsyncEnumerable.

Methods

AggregateAsync

static Task<TSource> AggregateAsync<TSource>(IAsyncQuery<TSource> source, Func<TSource, TSource, TSource> aggregator)

Applies an accumulator function over an async sequence.

  • source — Source async query
  • aggregator — Function that is called for each element as it arrives, starting from the second element. The first argument will the first element of the sequence and then the value returned by the previous invocation. The second argument will be the current element. The returned value will be passed to the next call, or will be the return value of the aggregation.

Returns: Last value returned by aggregator if the query returns two or more elements. The element itself if the query returns only one element.

static Task<TAggregate> AggregateAsync<TSource, TAggregate>(IAsyncQuery<TSource> source, TAggregate seed, Func<TAggregate, TSource, TAggregate> aggregator)

Applies an accumulator function over an async sequence.

  • source — Source async query
  • seed — Initial value for the aggregate that is passed as the first argument to aggregator
  • aggregator — Function that is called for each element as it arrives. The result will be passed back to the next function call for the following element.
// query that results a set of integers
IAsyncQuery<int> query = ...;
// manually compute the sum of all integers
long sum = await query.AggregateAsync(
	0L, // use a long for the sum
	(sum, x) => sum + x // add to the sum
);

static Task<TAccumulator> AggregateAsync<TSource, TAccumulator>(IAsyncQuery<TSource> source, TAccumulator accumulator, Action<TAccumulator, TSource> aggregator)

Applies an accumulator function over an async sequence.

  • source — Source async query
  • accumulator — Reference that is passed as the first argument to aggregator, usually a list or buffer of some kind.
  • aggregator — Action that is called for each element as it arrives. The action should mutate the accumulator (adding to a list or buffer, updating some state, ...).
// query that results a set of strings, some may be empty
IAsyncQuery<string> query = ...;
// buffer all the non-empty values
List<string> result = await query.AggregateAsync(
	[ ], // starts with an empty list
	(buffer, x) => { if (!string.IsNullOrEmpty(x)) buffer.Add(x) } // keep non-empty elements
);

static Task<TResult> AggregateAsync<TSource, TAggregate, TResult>(IAsyncQuery<TSource> source, TAggregate seed, Func<TAggregate, TSource, TAggregate> aggregator, Func<TAggregate, TResult> resultSelector)

Applies an accumulator function over an async sequence.

  • source — Source async query
  • seed — Initial value for the aggregate that is passed as the first argument to aggregator
  • aggregator — Function that is called for each element as it arrives. The result will be passed back to the next function call for the following element.
  • resultSelector — Function that is called with the last aggregate value (or seed if the query is empty), and computes the final result.

Returns: The value returned by resultSelector.

// query that returns a set of integers
IAsyncQuery<int> query = ...;
// compute the average value of the results
double average = await query.AggregateAsync(
    (Sum: 0L, Size: 0), // initial seed
    (acc, x) => (acc.Sum + x, acc.Size + 1), // sum the xs, and increment count
    (acc) => (double) acc.Sum / acc.Size // compute the average (expressed as a double)
);

static Task<TResult> AggregateAsync<TSource, TAccumulator, TResult>(IAsyncQuery<TSource> source, TAccumulator accumulator, Action<TAccumulator, TSource> aggregator, Func<TAccumulator, TResult> resultSelector)

Applies an accumulator function over an async sequence.

  • source — Source async query
  • accumulator — Value that is passed as the first argument to aggregator
  • aggregator — Action that is called for each element as it arrives.
  • resultSelector — Function that is called with the last aggregate value (or accumulator if the query is empty), and computes the final result.
// query that returns a set of strings, in some deterministic order
IAsyncQuery<string> query = ...;
// compute the aggregate hash of all the strings
var hash = await query.AggregateAsync(
    new FancyHashAggregator(/* ... */), // initializes the inner aggregator
    (fha, x) => fha.Append(x), // append the current result to the hash
    (fha) => fha.ComputeHash(), // compute the final hash value
);

AllAsync

static Task<bool> AllAsync<T>(IAsyncQuery<T> source, Func<T, bool> predicate)

Determines whether any element of an async sequence satisfies a condition.

static Task<bool> AllAsync<T>(IAsyncQuery<T> source, Func<T, CancellationToken, Task<bool>> predicate)

Determines whether any element of an async sequence satisfies a condition.

AnyAsync

static Task<bool> AnyAsync<T>(IAsyncQuery<T> source)

Determines whether an async sequence contains any elements.

This is the logical equivalent to "source.Count() > 0" but can be better optimized by some providers

static Task<bool> AnyAsync<T>(IAsyncQuery<T> source, Func<T, bool> predicate)

Determines whether any element of an async sequence satisfies a condition.

static Task<bool> AnyAsync<T>(IAsyncQuery<T> source, Func<T, CancellationToken, Task<bool>> predicate)

Determines whether any element of an async sequence satisfies a condition.

Batch

static IAsyncLinqQuery<TSource[]> Batch<TSource>(IAsyncQuery<TSource> source, int batchSize)

Buffers the items of a source sequence, and outputs a sequence of fixed-sized arrays.

  • source — Source sequence that will be cut into chunks containing at most batchSize items.
  • batchSize — Number of items per batch. The last batch may contain fewer items, but should never be empty.

Returns: Sequence of arrays of size batchSize, except the last batch which can have fewer items.

This operator does not care about the latency of each item, and will always try to fill each batch completely, before outputting a result. If you are working on an inner sequence that is bursty in nature, where items arrives in waves, you should use which attempts to minimize the latency by outputting incomplete batches if needed.

Between

static IAsyncLinqQuery<int> Between(int beginInclusive, int endExclusive, CancellationToken ct = null)

Generates a sequence of integral numbers between two bounds.

  • beginInclusive — The value of the first integer in the sequence.
  • endExclusive — The value at which the sequence stops iterating.
  • ct — Token used to cancel the execution of this query

Returns: An IAsyncLinqQuery that contains a range of sequential integral numbers from beginInclusive (included) to endExclusive (excluded).

The sequence is empty if is greater than or equal to

static IAsyncLinqQuery<long> Between(long beginInclusive, long endExclusive, CancellationToken ct = null)

Generates a sequence of integral numbers between two bounds.

  • beginInclusive — The value of the first integer in the sequence.
  • endExclusive — The value at which the sequence stops iterating.
  • ct — Token used to cancel the execution of this query

Returns: An IAsyncLinqQuery that contains a range of sequential integral numbers from beginInclusive (included) to endExclusive (excluded).

The sequence is empty if is greater than or equal to

static IAsyncLinqQuery<TNumber> Between<TNumber>(TNumber beginInclusive, TNumber endExclusive, CancellationToken ct = null)

Generates a sequence of integral numbers between two bounds.

  • beginInclusive — The value of the first integer in the sequence.
  • endExclusive — The value at which the sequence stops iterating.
  • ct — Token used to cancel the execution of this query

Returns: An IAsyncLinqQuery that contains a range of sequential integral numbers from beginInclusive (included) to endExclusive (excluded).

The sequence is empty if is greater than or equal to

static IAsyncLinqQuery<TValue> Between<TValue>(TValue beginInclusive, TValue endExclusive, Func<TValue, TValue> successor, CancellationToken ct = null)

Generates a sequence of integral numbers between two bounds.

  • beginInclusive — The value of the first integer in the sequence.
  • endExclusive — The value at which the sequence stops iterating.
  • successor — Function which is called to produce the next element in the sequence of result. It MUST always return an element that is strictly greater than its input, otherwise the sequence will never terminate.
  • ct — Token used to cancel the execution of this query

Returns: An IAsyncLinqQuery that contains a range of sequential integral numbers from beginInclusive (included) to endExclusive (excluded).

The sequence is empty if is greater than or equal to

static IAsyncLinqQuery<TValue> Between<TValue>(TValue beginInclusive, TValue endExclusive, Func<TValue, TValue> successor, IComparer<TValue> comparer, CancellationToken ct = null)

Generates a sequence of integral numbers between two bounds.

  • beginInclusive — The value of the first integer in the sequence.
  • endExclusive — The value at which the sequence stops iterating.
  • successor — Function which is called to produce the next element in the sequence of result. It MUST always return an element that is strictly greater than its input, otherwise the sequence will never terminate.
  • comparer — Instance use to compare values in the sequence. The sequence will continue enumerating as long as this comparing the current cursor with endExclusive returns a negative value.
  • ct — Token used to cancel the execution of this query

Returns: An IAsyncLinqQuery that contains a range of sequential integral numbers from beginInclusive (included) to endExclusive (excluded).

The sequence is empty if is greater than or equal to , according to .

CountAsync

static Task<int> CountAsync<T>(IAsyncQuery<T> source)

Returns the number of elements in an async sequence.

static Task<int> CountAsync<T>(IAsyncQuery<T> source, Func<T, bool> predicate)

Returns a number that represents how many elements in the specified async sequence satisfy a condition.

static Task<int> CountAsync<T>(IAsyncQuery<T> source, Func<T, CancellationToken, Task<bool>> predicate)

Returns a number that represents how many elements in the specified async sequence satisfy a condition.

Create

static IAsyncQuery<TResult> Create<TResult>(Func<object, AsyncIterationHint, CancellationToken, IAsyncEnumerator<TResult>> factory, object state, CancellationToken ct)

Create a new async query from a factory method

  • factory — Factory method called when the query starts iterating. Must return an async enumerator
  • state — Caller-provided state that will be passed to the factory method
  • ct — Cancellation token for this query

Returns: New async query

Defer

static IAsyncLinqQuery<TResult> Defer<TResult>(Func<IAsyncQuery<TResult>> factory, CancellationToken ct)

Creates a new async query from a factory that will be invoked on the first iteration

static IAsyncLinqQuery<TResult> Defer<TResult>(Func<Task<IAsyncQuery<TResult>>> factory, CancellationToken ct)

Creates a new async query from a factory that will be invoked on the first iteration

static IAsyncLinqQuery<TResult> Defer<TResult>(Func<CancellationToken, Task<IAsyncQuery<TResult>>> factory, CancellationToken ct)

Creates a new async query from a factory that will be invoked on the first iteration

static IAsyncLinqQuery<TResult> Defer<TResult>(Func<CancellationToken, Task<IAsyncLinqQuery<TResult>>> factory, CancellationToken ct)

Creates a new async query from a factory that will be invoked on the first iteration

static IAsyncLinqQuery<TResult> Defer<TResult>(Func<CancellationToken, Task<IAsyncEnumerable<TResult>>> factory, CancellationToken ct)

Creates a new async query from a factory that will be invoked on the first iteration

static IAsyncLinqQuery<TResult> Defer<TState, TResult>(TState state, Func<TState, IAsyncQuery<TResult>> factory, CancellationToken ct)

Creates a new async query from a factory that will be invoked on the first iteration

static IAsyncLinqQuery<TResult> Defer<TState, TResult>(TState state, Func<TState, Task<IAsyncQuery<TResult>>> factory, CancellationToken ct)

Creates a new async query from a factory that will be invoked on the first iteration

static IAsyncLinqQuery<TResult> Defer<TState, TResult>(TState state, Func<TState, CancellationToken, Task<IAsyncQuery<TResult>>> factory, CancellationToken ct)

Creates a new async query from a factory that will be invoked on the first iteration

static IAsyncLinqQuery<TResult> Defer<TState, TResult>(TState state, Func<TState, Task<IAsyncEnumerable<TResult>>> factory, CancellationToken ct)

Creates a new async query from a factory that will be invoked on the first iteration

static IAsyncLinqQuery<TResult> Defer<TState, TResult>(TState state, Func<TState, CancellationToken, Task<IAsyncEnumerable<TResult>>> factory, CancellationToken ct)

Creates a new async query from a factory that will be invoked on the first iteration

static IAsyncLinqQuery<TResult> Defer<TState, TResult>(TState state, Func<TState, CancellationToken, Task<IAsyncLinqQuery<TResult>>> factory, CancellationToken ct)

Creates a new async query from a factory that will be invoked on the first iteration

Distinct

static IAsyncLinqQuery<TSource> Distinct<TSource>(IAsyncQuery<TSource> source, IEqualityComparer<TSource> comparer = null)

ElementAtAsync

static Task<T> ElementAtAsync<T>(IAsyncQuery<T> source, int index)

Returns the element at a specific location of an async sequence, or an exception if there are not enough elements

ElementAtOrDefaultAsync

static Task<T> ElementAtOrDefaultAsync<T>(IAsyncQuery<T> source, int index)

Returns the element at a specific location of an async sequence, or the default value for the type if there are not enough elements

Empty

static IAsyncLinqQuery<T> Empty<T>()

Returns an empty async sequence

FirstAsync

static Task<T> FirstAsync<T>(IAsyncQuery<T> source)

Returns the first element of an async sequence, or an exception if it is empty

static Task<T> FirstAsync<T>(IAsyncQuery<T> source, Func<T, bool> predicate)

Returns the first element of an async sequence, or an exception if it is empty

static Task<T> FirstAsync<T>(IAsyncQuery<T> source, Func<T, CancellationToken, Task<bool>> predicate)

Returns the first element of an async sequence, or an exception if it is empty

FirstOrDefaultAsync

static Task<T> FirstOrDefaultAsync<T>(IAsyncQuery<T> source)

Returns the first element of an async sequence, or the default value for the type if it is empty

static Task<T> FirstOrDefaultAsync<T>(IAsyncQuery<T> source, T defaultValue)

Returns the first element of an async sequence, or the default value for the type if it is empty

static Task<T> FirstOrDefaultAsync<T>(IAsyncQuery<T> source, Func<T, bool> predicate)

Returns the first element of an async sequence, or the default value for the type if it is empty

static Task<T> FirstOrDefaultAsync<T>(IAsyncQuery<T> source, Func<T, CancellationToken, Task<bool>> predicate)

Returns the first element of an async sequence, or the default value for the type if it is empty

static Task<T> FirstOrDefaultAsync<T>(IAsyncQuery<T> source, Func<T, bool> predicate, T defaultValue)

Returns the first element of an async sequence, or the default value for the type if it is empty

static Task<T> FirstOrDefaultAsync<T>(IAsyncQuery<T> source, Func<T, CancellationToken, Task<bool>> predicate, T defaultValue)

Returns the first element of an async sequence, or the default value for the type if it is empty

ForEachAsync

static Task ForEachAsync<TElement>(IAsyncQuery<TElement> source, Action<TElement> action)

Execute an action for each element of an async sequence

static Task ForEachAsync<TElement>(IAsyncQuery<TElement> source, Func<TElement, Task> asyncAction)

Executes an async action for each element of an async sequence

static Task ForEachAsync<TElement>(IAsyncQuery<TElement> source, Func<TElement, CancellationToken, Task> asyncAction)

Executes an async action for each element of an async sequence

static Task ForEachAsync<TState, TElement>(IAsyncQuery<TElement> source, TState state, Action<TState, TElement> action)

Executes an action for each element of an async sequence

FromTask

static IAsyncLinqQuery<T> FromTask<T>(Func<CancellationToken, Task<T>> asyncLambda, CancellationToken ct)

Wraps an async lambda into an async sequence that will return the result of the lambda

async Task<R> ProcessQuery<T, R>(IAsyncQuery<T> query) { ... }
// creates a "singleton" query from the result of an async method, and pass this to a method that requires an IAsyncQuery<T>
var result = ProcessQuery(AsyncQuery.FromTask(SomeAsyncComputation(...), stoppingToken);

GetCancellableAsyncEnumerator

static IAsyncEnumerator<T> GetCancellableAsyncEnumerator<T>(IAsyncQuery<T> query, AsyncIterationHint hint, CancellationToken ct)

Helper method that checks that the cancellation token is the same as the source

This is used to simplify the pattern of adapting calls.

static Task<TSource> Head<TSource>(IAsyncQuery<TSource> source, bool single, bool orDefault, TSource defaultValue)

Helper async method to get the first element of an async query

  • source — Source async query
  • single — If true, the sequence must contain at most one element
  • orDefault — When the sequence is empty: If true then returns the default value for the type. Otherwise, throws an exception
  • defaultValue — Value that is returned when orDefault if true and the query does not return any results.

Returns: Value of the first element of the sequence, or the default value, or an exception (depending on single and orDefault

LastAsync

static Task<T> LastAsync<T>(IAsyncQuery<T> source)

Returns the last element of an async sequence, or an exception if it is empty

static Task<T> LastAsync<T>(IAsyncQuery<T> source, Func<T, bool> predicate)

Returns the last element of an async sequence, or an exception if it is empty

static Task<T> LastAsync<T>(IAsyncQuery<T> source, Func<T, CancellationToken, Task<bool>> predicate)

Returns the last element of an async sequence, or an exception if it is empty

LastOrDefaultAsync

static Task<T> LastOrDefaultAsync<T>(IAsyncQuery<T> source)

Returns the last element of an async sequence, or the default value for the type if it is empty

static Task<T> LastOrDefaultAsync<T>(IAsyncQuery<T> source, T defaultValue)

Returns the last element of an async sequence, or the default value for the type if it is empty

static Task<T> LastOrDefaultAsync<T>(IAsyncQuery<T> source, Func<T, bool> predicate)

Returns the last element of an async sequence, or the default value for the type if it is empty

static Task<T> LastOrDefaultAsync<T>(IAsyncQuery<T> source, Func<T, CancellationToken, Task<bool>> predicate)

Returns the last element of an async sequence, or the default value for the type if it is empty

static Task<T> LastOrDefaultAsync<T>(IAsyncQuery<T> source, Func<T, bool> predicate, T defaultValue)

Returns the last element of an async sequence, or the default value for the type if it is empty

static Task<T> LastOrDefaultAsync<T>(IAsyncQuery<T> source, Func<T, CancellationToken, Task<bool>> predicate, T defaultValue)

Returns the last element of an async sequence, or the default value for the type if it is empty

MaxAsync

static Task<T> MaxAsync<T>(IAsyncQuery<T> source, IComparer<T> comparer = null)

Returns the largest value in the specified async sequence

MinAsync

static Task<T> MinAsync<T>(IAsyncQuery<T> source, IComparer<T> comparer = null)

Returns the smallest value in the specified async sequence

Observe

static IAsyncLinqQuery<TSource> Observe<TSource>(IAsyncQuery<TSource> source, Action<TSource> handler)

Execute an action on each item passing through the sequence, without modifying the original sequence

The is execute inline before passing the item down the line, and should not block

static IAsyncLinqQuery<TSource> Observe<TSource>(IAsyncQuery<TSource> source, Func<TSource, CancellationToken, Task> asyncHandler)

Execute an action on each item passing through the sequence, without modifying the original sequence

The is execute inline before passing the item down the line, and should not block

OrderBy

static IOrderedAsyncQuery<TSource> OrderBy<TSource, TKey>(IAsyncQuery<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer = null)

OrderByDescending

static IOrderedAsyncQuery<TSource> OrderByDescending<TSource, TKey>(IAsyncQuery<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer = null)

Prefetch

static IAsyncLinqQuery<TSource> Prefetch<TSource>(IAsyncQuery<TSource> source)

Always prefetch the next item from the inner sequence.

  • source — Source sequence that has a high latency, and from which we want to prefetch a set number of items.

Returns: Sequence that prefetch the next item, when outputting the current item.

This iterator can help smooth out the query pipeline when every call to the inner sequence has a somewhat high latency (ex: reading the next page of results from the database). Avoid pre-fetching from a source that is already reading from a buffer of results.

static IAsyncLinqQuery<TSource> Prefetch<TSource>(IAsyncEnumerable<TSource> source, CancellationToken ct = null)

Always prefetch the next item from the inner sequence.

  • source — Source sequence that has a high latency, and from which we want to prefetch a set number of items.
  • ct — Cancellation token for this query

Returns: Sequence that prefetch the next item, when outputting the current item.

This iterator can help smooth out the query pipeline when every call to the inner sequence has a somewhat high latency (ex: reading the next page of results from the database). Avoid pre-fetching from a source that is already reading from a buffer of results.

static IAsyncLinqQuery<TSource> Prefetch<TSource>(IAsyncQuery<TSource> source, int prefetchCount)

Prefetch a certain number of items from the inner sequence, before outputting the results one by one.

  • source — Source sequence that has a high latency, and from which we want to prefetch a set number of items.
  • prefetchCount — Maximum number of items to buffer from the source before they are consumed by the rest of the query.

Returns: Sequence that returns items from a buffer of pre-fetched list.

This iterator can help smooth out the query pipeline when every call to the inner sequence has a somewhat high latency (ex: reading the next page of results from the database). Avoid pre-fetching from a source that is already reading from a buffer of results.

Pump

static IAsyncEnumerable<TResult> Pump<TResult>(Func<ChannelWriter<TResult>, Task> handler, CancellationToken ct)

Range

static IAsyncLinqQuery<int> Range(int start, int count, CancellationToken ct = null)

Generates a sequence of integral numbers within a specified range.

  • start — The value of the first integer in the sequence.
  • count — The number of sequential integers to generate.
  • ct — Token used to cancel the execution of this query

Returns: An IAsyncLinqQuery that contains a range of sequential integral numbers.

static IAsyncLinqQuery<TNumber> Range<TNumber>(TNumber start, TNumber delta, int count, CancellationToken ct = null)

Generates a sequence of integral numbers within a specified range.

  • start — The value of the first element returned by the query.
  • delta — The value that is added to each value return by the query.
  • count — The number of elements returned by the query.
  • ct — Token used to cancel the execution of this query

Returns: An IAsyncQuery that contains a range of sequential numbers.

Select

static IAsyncLinqQuery<TResult> Select<TSource, TResult>(IAsyncQuery<TSource> source, Func<TSource, TResult> selector)

Projects each element of an async sequence into a new form.

static IAsyncLinqQuery<TResult> Select<TSource, TResult>(IAsyncQuery<TSource> source, Func<TSource, int, TResult> selector)

Projects each element of an async sequence into a new form.

static IAsyncLinqQuery<TResult> Select<TSource, TResult>(IAsyncQuery<TSource> source, Func<TSource, CancellationToken, Task<TResult>> selector)

Projects each element of an async sequence into a new form.

static IAsyncLinqQuery<TResult> Select<TSource, TResult>(IAsyncQuery<TSource> source, Func<TSource, int, CancellationToken, Task<TResult>> selector)

Projects each element of an async sequence into a new form.

SelectMany

static IAsyncLinqQuery<TResult> SelectMany<TSource, TResult>(IAsyncQuery<TSource> source, Func<TSource, IEnumerable<TResult>> selector)

Projects each element of an async sequence to an IEnumerable and flattens the resulting sequences into one async sequence.

static IAsyncLinqQuery<TResult> SelectMany<TSource, TResult>(IAsyncQuery<TSource> source, Func<TSource, IAsyncEnumerable<TResult>> selector)

Projects each element of an async sequence to an IAsyncEnumerable and flattens the resulting sequences into one async sequence.

static IAsyncLinqQuery<TResult> SelectMany<TSource, TResult>(IAsyncQuery<TSource> source, Func<TSource, IAsyncQuery<TResult>> selector)

Projects each element of an async sequence to an IAsyncQuery and flattens the resulting sequences into one async sequence.

static IAsyncLinqQuery<TResult> SelectMany<TSource, TResult>(IAsyncQuery<TSource> source, Func<TSource, CancellationToken, Task<IEnumerable<TResult>>> selector)

Projects each element of an async sequence to an IEnumerable and flattens the resulting sequences into one async sequence.

static IAsyncLinqQuery<TResult> SelectMany<TSource, TCollection, TResult>(IAsyncQuery<TSource> source, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector)

Projects each element of an async sequence to an IEnumerable flattens the resulting sequences into one async sequence, and invokes a result selector function on each element therein.

static IAsyncLinqQuery<TResult> SelectMany<TSource, TCollection, TResult>(IAsyncQuery<TSource> source, Func<TSource, CancellationToken, Task<IEnumerable<TCollection>>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector)

Projects each element of an async sequence to an IEnumerable flattens the resulting sequences into one async sequence, and invokes a result selector function on each element therein.

SelectParallel

static IAsyncLinqQuery<TResult> SelectParallel<TSource, TResult>(IAsyncQuery<TSource> source, Func<TSource, CancellationToken, Task<TResult>> asyncSelector, ParallelAsyncQueryOptions options = null)

Projects each element of an async sequence into a new form, allowing concurrent execution.

This method can process multiple elements concurrently which could complete out of order, but the output will keep in the same ordering as the source query.

The maximum number of current tasks can be controlled via MaxConcurrency.

The TaskScheduler that is used to process each element can be controller via Scheduler.

SingleAsync

static Task<T> SingleAsync<T>(IAsyncQuery<T> source)

Returns the first and only element of an async sequence, or an exception if it is empty or have two or more elements

Will need to call MoveNext at least twice to ensure that there is no second element.

static Task<T> SingleAsync<T>(IAsyncQuery<T> source, Func<T, bool> predicate)

Returns the first and only element of an async sequence, or an exception if it is empty or have two or more elements

Will need to call MoveNext at least twice to ensure that there is no second element.

static Task<T> SingleAsync<T>(IAsyncQuery<T> source, Func<T, CancellationToken, Task<bool>> predicate)

Returns the first and only element of an async sequence, or an exception if it is empty or have two or more elements

Will need to call MoveNext at least twice to ensure that there is no second element.

SingleOrDefaultAsync

static Task<T> SingleOrDefaultAsync<T>(IAsyncQuery<T> source)

Returns the first and only element of an async sequence, the default value for the type if it is empty, or an exception if it has two or more elements

Will need to call MoveNext at least twice to ensure that there is no second element.

static Task<T> SingleOrDefaultAsync<T>(IAsyncQuery<T> source, T defaultValue)

Returns the first and only element of an async sequence, the default value for the type if it is empty, or an exception if it has two or more elements

Will need to call MoveNext at least twice to ensure that there is no second element.

static Task<T> SingleOrDefaultAsync<T>(IAsyncQuery<T> source, Func<T, bool> predicate)

Returns the first and only element of an async sequence, the default value for the type if it is empty, or an exception if it has two or more elements

Will need to call MoveNext at least twice to ensure that there is no second element.

static Task<T> SingleOrDefaultAsync<T>(IAsyncQuery<T> source, Func<T, CancellationToken, Task<bool>> predicate)

Returns the first and only element of an async sequence, the default value for the type if it is empty, or an exception if it has two or more elements

Will need to call MoveNext at least twice to ensure that there is no second element.

static Task<T> SingleOrDefaultAsync<T>(IAsyncQuery<T> source, Func<T, bool> predicate, T defaultValue)

Returns the first and only element of an async sequence, the default value for the type if it is empty, or an exception if it has two or more elements

Will need to call MoveNext at least twice to ensure that there is no second element.

static Task<T> SingleOrDefaultAsync<T>(IAsyncQuery<T> source, Func<T, CancellationToken, Task<bool>> predicate, T defaultValue)

Returns the first and only element of an async sequence, the default value for the type if it is empty, or an exception if it has two or more elements

Will need to call MoveNext at least twice to ensure that there is no second element.

Singleton

static IAsyncLinqQuery<T> Singleton<T>(T value, CancellationToken ct = null)

Returns an async sequence with a single element, which is a constant

static IAsyncLinqQuery<T> Singleton<T>(Func<T> selector, CancellationToken ct = null)

Returns an async sequence which will produce a single element, using the specified lambda

  • selector — Lambda that will be called once per iteration, to produce the single element of this sequence
  • ct — Token used to cancel the execution of this query

If the sequence is iterated multiple times, then will be called once for each iteration.

static IAsyncLinqQuery<T> Singleton<T>(Func<CancellationToken, Task<T>> selector, CancellationToken ct = null)

Returns an async sequence which will produce a single element, using the specified lambda

  • selector — Lambda that will be called once per iteration, to produce the single element of this sequence
  • ct — Token used to cancel the execution of this query

If the sequence is iterated multiple times, then will be called once for each iteration.

static IAsyncLinqQuery<T> Singleton<T>(Func<Task<T>> selector, CancellationToken ct = null)

Returns an async sequence which will produce a single element, using the specified lambda

  • selector — Lambda that will be called once per iteration, to produce the single element of this sequence
  • ct — Token used to cancel the execution of this query

If the sequence is iterated multiple times, then will be called once for each iteration.

Skip

static IAsyncLinqQuery<TSource> Skip<TSource>(IAsyncQuery<TSource> source, int count)

Skips the first elements of an async sequence.

SumAsync

static Task<T> SumAsync<T>(IAsyncQuery<T> source)

Returns the sum of all elements in the specified async sequence that satisfy a condition.

static Task<T?> SumAsync<T>(IAsyncQuery<T?> source)

Returns the sum of all elements in the specified async sequence that satisfy a condition.

static Task<int> SumAsync(IAsyncQuery<int> source)

Returns the sum of all elements in the specified async sequence.

static Task<int?> SumAsync(IAsyncQuery<int?> source)

Returns the sum of all elements in the specified async sequence.

static Task<long> SumAsync(IAsyncQuery<long> source)

Returns the sum of all elements in the specified async sequence.

static Task<long?> SumAsync(IAsyncQuery<long?> source)

Returns the sum of all elements in the specified async sequence.

static Task<float> SumAsync(IAsyncQuery<float> source)

Returns the sum of all elements in the specified async sequence.

static Task<float?> SumAsync(IAsyncQuery<float?> source)

Returns the sum of all elements in the specified async sequence.

static Task<double> SumAsync(IAsyncQuery<double> source)

Returns the sum of all elements in the specified async sequence.

static Task<double?> SumAsync(IAsyncQuery<double?> source)

Returns the sum of all elements in the specified async sequence.

static Task<decimal> SumAsync(IAsyncQuery<decimal> source)

Returns the sum of all elements in the specified async sequence.

static Task<decimal?> SumAsync(IAsyncQuery<decimal?> source)

Returns the sum of all elements in the specified async sequence.

Take

static IAsyncLinqQuery<TSource> Take<TSource>(IAsyncQuery<TSource> source, int count)

Returns a specified number of contiguous elements from the start of an async sequence.

static IAsyncLinqQuery<TSource> Take<TSource>(IAsyncQuery<TSource> source, Range range)

Returns a specified number of contiguous elements from the start of an async sequence.

TakeWhile

static IAsyncLinqQuery<TSource> TakeWhile<TSource>(IAsyncQuery<TSource> source, Func<TSource, bool> condition)

Returns elements from an async sequence as long as a specified condition is true, and then skips the remaining elements.

static IAsyncLinqQuery<TSource> TakeWhile<TSource>(IAsyncQuery<TSource> source, Func<TSource, bool> condition, out QueryStatistics<bool> stopped)

Returns elements from an async sequence as long as a specified condition is true, and then skips the remaining elements.

ThenBy

static IOrderedAsyncQuery<TSource> ThenBy<TSource, TKey>(IOrderedAsyncQuery<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer = null)

ThenByDescending

static IOrderedAsyncQuery<TSource> ThenByDescending<TSource, TKey>(IOrderedAsyncQuery<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer = null)

ToArrayAsync

static Task<T[]> ToArrayAsync<T>(IAsyncQuery<T> source)

Creates an array from an async sequence.

ToAsyncEnumerable

static IAsyncEnumerable<T> ToAsyncEnumerable<T>(IAsyncQuery<T> source, AsyncIterationHint hint = 0)

Adapts this query into the equivalent IAsyncEnumerable

  • source — Source query that will be adapted into an IAsyncEnumerable
  • hint — Hint passed to the source provider.

Returns: Sequence that will asynchronously return the results of this query.

For best performance, the caller should take care to provide a hint that matches how this query will be consumed downstream.

If the hint does not match, performance may be degraded. For example, if the caller will consumer this query using await foreach or ToListAsync, but uses Iterator, the provider may fetch small pages initially, before ramping up. The opposite is also true if the caller uses All but consumes the query using AnyAsync() or FirstOrDefaultAsync, the provider may fetch large pages and waste most of it except the first few elements.

ToAsyncQuery

static IAsyncLinqQuery<T> ToAsyncQuery<T>(IEnumerable<T> source, CancellationToken ct)

Wraps an IEnumerable into an IAsyncLinqQuery that will return the same elements.

// starts with a "regular" IEnumerable<T>
var items = Enumerable.Range(0, 10).Select(...).Where(...);
// switch to an IAsyncQuery<T>
var query = await enumerable
	.ToAsyncQuery(stoppingToken) // inject the cancellation token here
	.Select(((x, ct) => SomeAsyncMethod(x, ct)) // call an async method
	.ToListAsync(); // return a list with the results

static IAsyncLinqQuery<T> ToAsyncQuery<T>(IAsyncEnumerable<T> source, CancellationToken ct = null)

Wraps an IAsyncEnumerable into an IAsyncLinqQuery that will return the same elements.

// we have an existing async enumerator that we want to use as a source
async IAsyncEnumerable<T> ComputeRange<T>(int start, int count, Func<int, Task<T>> callback)
{
	while(count-- > 0)
	{

		yield return await callback(start++);
	}
}

// but we need pass this to a method that wants an async query:
Task<T> PostProcess(IAsyncQuery<T> query) { ... }

// we just need to wrap one type of async enumerable into another
var query = ComputeRange(42, 25, (x) => /*...*/).ToAsyncQuery(stoppingToken);
// and pass the resulting query to the post-processing step
var result = await PostProcess(query);

ToDictionaryAsync

static Task<Dictionary<TKey, TValue>> ToDictionaryAsync<TKey, TValue>(IAsyncQuery<KeyValuePair<TKey, TValue>> source, IEqualityComparer<TKey> comparer = null)

Creates a Dictionary from an async sequence of pairs of keys and values.

static Task<Dictionary<TKey, TSource>> ToDictionaryAsync<TSource, TKey>(IAsyncQuery<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer = null)

Creates a Dictionary from an async sequence according to a specified key selector function and key comparer.

static Task<Dictionary<TKey, TElement>> ToDictionaryAsync<TSource, TKey, TElement>(IAsyncQuery<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer = null)

Creates a Dictionary from an async sequence according to a specified key selector function, a comparer, and an element selector function.

ToHashSetAsync

static Task<HashSet<T>> ToHashSetAsync<T>(IAsyncQuery<T> source, IEqualityComparer<T> comparer = null)

Creates a Hashset from an async sequence.

ToImmutableArrayAsync

static Task<ImmutableArray<T>> ToImmutableArrayAsync<T>(IAsyncQuery<T> source)

Creates a list from an async sequence.

ToListAsync

static Task<List<T>> ToListAsync<T>(IAsyncQuery<T> source)

Creates a list from an async sequence.

Where

static IAsyncLinqQuery<TResult> Where<TResult>(IAsyncQuery<TResult> source, Func<TResult, bool> predicate)

Filters an async sequence of values based on a predicate.

static IAsyncLinqQuery<TResult> Where<TResult>(IAsyncQuery<TResult> source, Func<TResult, int, bool> predicate)

Filters an async sequence of values based on a predicate.

static IAsyncLinqQuery<TResult> Where<TResult>(IAsyncQuery<TResult> source, Func<TResult, CancellationToken, Task<bool>> predicate)

Filters an async sequence of values based on a predicate.

static IAsyncLinqQuery<TResult> Where<TResult>(IAsyncQuery<TResult> source, Func<TResult, int, CancellationToken, Task<bool>> predicate)

Filters an async sequence of values based on a predicate.

Window

static IAsyncLinqQuery<TSource[]> Window<TSource>(IAsyncQuery<TSource> source, int maxWindowSize)

Buffers the items of a bursty sequence, into a sequence of variable-sized arrays made up of items that where produced in a very short timespan.

  • source — Source sequence, that produces bursts of items, produced from the same page of results, before reading the next page.
  • maxWindowSize — Maximum number of items to return in a single window. If more items arrive at the same time, a new window will be opened with the rest of the items.

Returns: Sequence of batches, where all the items of a single batch arrived at the same time. A batch is closed once the next call to MoveNext() on the inner sequence does not complete immediately. Batches can be smaller than maxWindowSize.

This should only be called on bursty asynchronous sequences, and when you want to process items in batches, without incurring the cost of latency between two pages of results. You should avoid using this operator on sequences where each call to MoveNext() is asynchronous, since it would only produce batches with only a single item.

WithCountStatistics

static IAsyncLinqQuery<TSource> WithCountStatistics<TSource>(IAsyncQuery<TSource> source, out QueryStatistics<int> counter)

Measure the number of items that pass through this point of the query

The values returned in are only safe to read once the query has ended

WithSizeStatistics

static IAsyncLinqQuery<KeyValuePair<Slice, Slice>> WithSizeStatistics(IAsyncQuery<KeyValuePair<Slice, Slice>> source, out QueryStatistics<KeyValueSizeStatistics> statistics)

Measure the number and size of slices that pass through this point of the query

The values returned in are only safe to read once the query has ended

static IAsyncLinqQuery<Slice> WithSizeStatistics(IAsyncQuery<Slice> source, out QueryStatistics<DataSizeStatistics> statistics)

Measure the number and sizes of the keys and values that pass through this point of the query

The values returned in are only safe to read once the query has ended