Generate.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Collections.Generic;
  5. namespace System.Linq
  6. {
  7. public static partial class EnumerableEx
  8. {
  9. /// <summary>
  10. /// Generates a sequence by mimicking a for loop.
  11. /// </summary>
  12. /// <typeparam name="TState">State type.</typeparam>
  13. /// <typeparam name="TResult">Result sequence element type.</typeparam>
  14. /// <param name="initialState">Initial state of the generator loop.</param>
  15. /// <param name="condition">Loop condition.</param>
  16. /// <param name="iterate">State update function to run after every iteration of the generator loop.</param>
  17. /// <param name="resultSelector">Result selector to compute resulting sequence elements.</param>
  18. /// <returns>Sequence obtained by running the generator loop, yielding computed elements.</returns>
  19. public static IEnumerable<TResult> Generate<TState, TResult>(TState initialState, Func<TState, bool> condition, Func<TState, TState> iterate, Func<TState, TResult> resultSelector)
  20. {
  21. if (condition == null)
  22. throw new ArgumentNullException(nameof(condition));
  23. if (iterate == null)
  24. throw new ArgumentNullException(nameof(iterate));
  25. if (resultSelector == null)
  26. throw new ArgumentNullException(nameof(resultSelector));
  27. return GenerateCore(initialState, condition, iterate, resultSelector);
  28. }
  29. private static IEnumerable<TResult> GenerateCore<TState, TResult>(TState initialState, Func<TState, bool> condition, Func<TState, TState> iterate, Func<TState, TResult> resultSelector)
  30. {
  31. for (var i = initialState; condition(i); i = iterate(i))
  32. {
  33. yield return resultSelector(i);
  34. }
  35. }
  36. }
  37. }