Generate.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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 EnumerableEx
  11. {
  12. /// <summary>
  13. /// Generates a sequence by mimicking a for loop.
  14. /// </summary>
  15. /// <typeparam name="TState">State type.</typeparam>
  16. /// <typeparam name="TResult">Result sequence element type.</typeparam>
  17. /// <param name="initialState">Initial state of the generator loop.</param>
  18. /// <param name="condition">Loop condition.</param>
  19. /// <param name="iterate">State update function to run after every iteration of the generator loop.</param>
  20. /// <param name="resultSelector">Result selector to compute resulting sequence elements.</param>
  21. /// <returns>Sequence obtained by running the generator loop, yielding computed elements.</returns>
  22. public static IEnumerable<TResult> Generate<TState, TResult>(TState initialState, Func<TState, bool> condition, Func<TState, TState> iterate, Func<TState, TResult> resultSelector)
  23. {
  24. if (condition == null)
  25. throw new ArgumentNullException(nameof(condition));
  26. if (iterate == null)
  27. throw new ArgumentNullException(nameof(iterate));
  28. if (resultSelector == null)
  29. throw new ArgumentNullException(nameof(resultSelector));
  30. return Generate_(initialState, condition, iterate, resultSelector);
  31. }
  32. private static IEnumerable<TResult> Generate_<TState, TResult>(TState initialState, Func<TState, bool> condition, Func<TState, TState> iterate, Func<TState, TResult> resultSelector)
  33. {
  34. for (var i = initialState; condition(i); i = iterate(i))
  35. yield return resultSelector(i);
  36. }
  37. }
  38. }