Generate.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading.Tasks;
  8. namespace System.Linq
  9. {
  10. public static partial class AsyncEnumerable
  11. {
  12. public static IAsyncEnumerable<TResult> Generate<TState, TResult>(TState initialState, Func<TState, bool> condition, Func<TState, TState> iterate, Func<TState, TResult> resultSelector)
  13. {
  14. if (condition == null)
  15. throw new ArgumentNullException(nameof(condition));
  16. if (iterate == null)
  17. throw new ArgumentNullException(nameof(iterate));
  18. if (resultSelector == null)
  19. throw new ArgumentNullException(nameof(resultSelector));
  20. return CreateEnumerable(
  21. () =>
  22. {
  23. var i = initialState;
  24. var started = false;
  25. var current = default(TResult);
  26. return CreateEnumerator(
  27. ct =>
  28. {
  29. var b = false;
  30. try
  31. {
  32. if (started)
  33. i = iterate(i);
  34. b = condition(i);
  35. if (b)
  36. current = resultSelector(i);
  37. }
  38. catch (Exception ex)
  39. {
  40. return TaskExt.Throw<bool>(ex);
  41. }
  42. if (!b)
  43. return TaskExt.False;
  44. if (!started)
  45. started = true;
  46. return TaskExt.True;
  47. },
  48. () => current,
  49. () => { }
  50. );
  51. });
  52. }
  53. }
  54. }