Generate.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. var i = initialState;
  23. var started = false;
  24. var current = default(TResult);
  25. return CreateEnumerator(
  26. ct =>
  27. {
  28. var b = false;
  29. try
  30. {
  31. if (started)
  32. i = iterate(i);
  33. b = condition(i);
  34. if (b)
  35. current = resultSelector(i);
  36. }
  37. catch (Exception ex)
  38. {
  39. return TaskExt.Throw<bool>(ex);
  40. }
  41. if (!b)
  42. return TaskExt.False;
  43. if (!started)
  44. started = true;
  45. return TaskExt.True;
  46. },
  47. () => current,
  48. () => { }
  49. );
  50. });
  51. }
  52. }
  53. }