// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace System.Linq { public static partial class EnumerableEx { /// /// Generates a sequence by mimicking a for loop. /// /// State type. /// Result sequence element type. /// Initial state of the generator loop. /// Loop condition. /// State update function to run after every iteration of the generator loop. /// Result selector to compute resulting sequence elements. /// Sequence obtained by running the generator loop, yielding computed elements. public static IEnumerable Generate(TState initialState, Func condition, Func iterate, Func resultSelector) { if (condition == null) throw new ArgumentNullException(nameof(condition)); if (iterate == null) throw new ArgumentNullException(nameof(iterate)); if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector)); return Generate_(initialState, condition, iterate, resultSelector); } private static IEnumerable Generate_(TState initialState, Func condition, Func iterate, Func resultSelector) { for (var i = initialState; condition(i); i = iterate(i)) yield return resultSelector(i); } } }