ToList.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 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. public static Task<List<TSource>> ToListAsync<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default)
  12. {
  13. if (source == null)
  14. throw Error.ArgumentNull(nameof(source));
  15. if (source is IAsyncIListProvider<TSource> listProvider)
  16. return listProvider.ToListAsync(cancellationToken).AsTask();
  17. return Core(source, cancellationToken);
  18. static async Task<List<TSource>> Core(IAsyncEnumerable<TSource> _source, CancellationToken _cancellationToken)
  19. {
  20. var list = new List<TSource>();
  21. await foreach (TSource item in _source.WithCancellation(_cancellationToken).ConfigureAwait(false))
  22. {
  23. list.Add(item);
  24. }
  25. return list;
  26. }
  27. }
  28. }
  29. }