LongCount.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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<long> LongCount<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
  12. {
  13. if (source == null)
  14. throw new ArgumentNullException(nameof(source));
  15. return source.Aggregate(0L, (c, _) => checked(c + 1), cancellationToken);
  16. }
  17. public static Task<long> LongCount<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate, CancellationToken cancellationToken)
  18. {
  19. if (source == null)
  20. throw new ArgumentNullException(nameof(source));
  21. if (predicate == null)
  22. throw new ArgumentNullException(nameof(predicate));
  23. return source.Where(predicate).Aggregate(0L, (c, _) => checked(c + 1), cancellationToken);
  24. }
  25. public static Task<long> LongCount<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, Task<bool>> predicate, CancellationToken cancellationToken)
  26. {
  27. if (source == null)
  28. throw new ArgumentNullException(nameof(source));
  29. if (predicate == null)
  30. throw new ArgumentNullException(nameof(predicate));
  31. return source.Where(predicate).Aggregate(0L, (c, _) => checked(c + 1), cancellationToken);
  32. }
  33. public static Task<long> LongCount<TSource>(this IAsyncEnumerable<TSource> source)
  34. {
  35. if (source == null)
  36. throw new ArgumentNullException(nameof(source));
  37. return LongCount(source, CancellationToken.None);
  38. }
  39. public static Task<long> LongCount<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, bool> predicate)
  40. {
  41. if (source == null)
  42. throw new ArgumentNullException(nameof(source));
  43. if (predicate == null)
  44. throw new ArgumentNullException(nameof(predicate));
  45. return LongCount(source, predicate, CancellationToken.None);
  46. }
  47. public static Task<long> LongCount<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, Task<bool>> predicate)
  48. {
  49. if (source == null)
  50. throw new ArgumentNullException(nameof(source));
  51. if (predicate == null)
  52. throw new ArgumentNullException(nameof(predicate));
  53. return LongCount(source, predicate, CancellationToken.None);
  54. }
  55. }
  56. }