ToList.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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>> ToList<TSource>(this IAsyncEnumerable<TSource> source)
  12. {
  13. if (source == null)
  14. throw new ArgumentNullException(nameof(source));
  15. return ToList(source, CancellationToken.None);
  16. }
  17. public static Task<List<TSource>> ToList<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  18. {
  19. if (source == null)
  20. throw new ArgumentNullException(nameof(source));
  21. if (source is IIListProvider<TSource> listProvider)
  22. return listProvider.ToListAsync(cancellationToken);
  23. return source.Aggregate(
  24. new List<TSource>(),
  25. (list, x) =>
  26. {
  27. list.Add(x);
  28. return list;
  29. },
  30. cancellationToken
  31. );
  32. }
  33. }
  34. }