ToList.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Linq
  8. {
  9. public static partial class AsyncEnumerable
  10. {
  11. /// <summary>
  12. /// Creates a list from an async-enumerable sequence.
  13. /// </summary>
  14. /// <typeparam name="TSource">The type of the elements in the source sequence.</typeparam>
  15. /// <param name="source">The source async-enumerable sequence to get a list of elements for.</param>
  16. /// <param name="cancellationToken">The optional cancellation token to be used for cancelling the sequence at any time.</param>
  17. /// <returns>An async-enumerable sequence containing a single element with a list containing all the elements of the source sequence.</returns>
  18. /// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
  19. /// <remarks>The return type of this operator differs from the corresponding operator on IEnumerable in order to retain asynchronous behavior.</remarks>
  20. public static ValueTask<List<TSource>> ToListAsync<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default)
  21. {
  22. if (source == null)
  23. throw Error.ArgumentNull(nameof(source));
  24. if (source is IAsyncIListProvider<TSource> listProvider)
  25. return listProvider.ToListAsync(cancellationToken);
  26. return Core(source, cancellationToken);
  27. static async ValueTask<List<TSource>> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  28. {
  29. var list = new List<TSource>();
  30. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  31. {
  32. list.Add(item);
  33. }
  34. return list;
  35. }
  36. }
  37. }
  38. }