// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT License.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace System.Linq
{
public static partial class AsyncEnumerable
{
///
/// Returns the element at a specified index in a sequence or a default value if the index is out of range.
///
/// The type of the elements in the source sequence.
/// async-enumerable sequence to return the element from.
/// The zero-based index of the element to retrieve.
/// The optional cancellation token to be used for cancelling the sequence at any time.
/// An async-enumerable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence.
/// is null.
/// is less than zero.
public static ValueTask ElementAtOrDefaultAsync(this IAsyncEnumerable source, int index, CancellationToken cancellationToken = default)
{
if (source == null)
throw Error.ArgumentNull(nameof(source));
return Core(source, index, cancellationToken);
static async ValueTask Core(IAsyncEnumerable source, int index, CancellationToken cancellationToken)
{
if (source is IAsyncPartition p)
{
var first = await p.TryGetElementAtAsync(index, cancellationToken).ConfigureAwait(false);
if (first.HasValue)
{
return first.Value;
}
}
if (index >= 0)
{
if (source is IList list)
{
if (index < list.Count)
{
return list[index];
}
}
else
{
await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
{
if (index == 0)
{
return item;
}
index--;
}
}
}
return default;
}
}
}
}