public static ValueTask <TSource> SingleOrDefaultAsync <TSource>(this IAsyncEnumerable <TSource> source, CancellationToken cancellationToken = default) { if (source == null) { throw Error.ArgumentNull(nameof(source)); } return(Core(source, cancellationToken)); async ValueTask <TSource> Core(IAsyncEnumerable <TSource> _source, CancellationToken _cancellationToken) { if (_source is IList <TSource> list) { switch (list.Count) { case 0: return(default); case 1: return(list[0]); } throw Error.MoreThanOneElement(); } await using (var e = _source.GetConfiguredAsyncEnumerator(_cancellationToken, false)) { if (!await e.MoveNextAsync()) { return(default);
static async ValueTask <TSource> Core(IAsyncEnumerable <TSource> source, CancellationToken cancellationToken) { if (source is IList <TSource> list) { switch (list.Count) { case 0: throw Error.NoElements(); case 1: return(list[0]); } throw Error.MoreThanOneElement(); } await using var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false); if (!await e.MoveNextAsync()) { throw Error.NoElements(); } var result = e.Current; if (await e.MoveNextAsync()) { throw Error.MoreThanOneElement(); } return(result); }
public static TSource SingleOrDefault <TSource>(this IEnumerable <TSource> source) { if (source == null) { throw Error.ArgumentNull("source"); } IList <TSource> list = source as IList <TSource>; if (list != null) { switch (list.Count) { case 0: return(default(TSource)); case 1: return(list[0]); } } else { using (IEnumerator <TSource> e = source.GetEnumerator()) { if (!e.MoveNext()) { return(default(TSource)); } TSource result = e.Current; if (!e.MoveNext()) { return(result); } } } throw Error.MoreThanOneElement(); }
static async ValueTask <TSource> Core(IAsyncEnumerable <TSource> source, CancellationToken cancellationToken) { if (source is IList <TSource> list) { return(list.Count switch { 0 => throw Error.NoElements(), 1 => list[0], _ => throw Error.MoreThanOneElement(), });
static async ValueTask <TSource> Core(IAsyncEnumerable <TSource> source, CancellationToken cancellationToken) { if (source is IList <TSource> list) { switch (list.Count) { case 0: return(default !); case 1: return(list[0]); } throw Error.MoreThanOneElement(); } await using (var e = source.GetConfiguredAsyncEnumerator(cancellationToken, false)) { if (!await e.MoveNextAsync()) { return(default !);