Generate.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. 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. {
  23. throw new ArgumentNullException(nameof(condition));
  24. }
  25. if (iterate == null)
  26. {
  27. throw new ArgumentNullException(nameof(iterate));
  28. }
  29. if (resultSelector == null)
  30. {
  31. throw new ArgumentNullException(nameof(resultSelector));
  32. }
  33. return GenerateCore(initialState, condition, iterate, resultSelector);
  34. }
  35. private static IEnumerable<TResult> GenerateCore<TState, TResult>(TState initialState, Func<TState, bool> condition, Func<TState, TState> iterate, Func<TState, TResult> resultSelector)
  36. {
  37. for (var i = initialState; condition(i); i = iterate(i))
  38. {
  39. yield return resultSelector(i);
  40. }
  41. }
  42. }
  43. }