- Manually increment an enumerator inside foreach loop
- foreach (DateTime time in times)
- {
- while (condition)
- {
- // perform action
- // move to next item
- (time as IEnumerator<DateTime>).MoveNext(); // will not let me do this
- }
- // code to execute after while condition is met
- }
- using (var enumerator = times.GetEnumerator())
- {
- DateTime time;
- while (enumerator.MoveNext())
- {
- time = enumerator.Current;
- // pre-condition code
- while (condition)
- {
- if (enumerator.MoveNext())
- {
- time = enumerator.Current;
- // condition code
- }
- else
- {
- condition = false;
- }
- }
- // post-condition code
- }
- }
- foreach (DateTime time in times)
- {
- if (condition)
- {
- // perform action
- continue;
- }
- // code to execute if condition is not met
- }
- foreach (DateTime time in times)
- {
- if (condition)
- {
- // perform action
- }
- else
- {
- // code to execute if condition is not met
- }
- }
- var times = new List<DateTime>()
- {
- DateTime.Now.AddDays(1), DateTime.Now.AddDays(2), DateTime.Now.AddDays(3), DateTime.Now.AddDays(4)
- };
- var cutoff = DateTime.Now.AddDays(2);
- var timesAfterCutoff = times.SkipWhile(datetime => datetime.CompareTo(cutoff) < 1)
- .Select(datetime => datetime);
- foreach (var dateTime in timesAfterCutoff)
- {
- Console.WriteLine(dateTime);
- }
- Console.ReadLine();
- public static void Main(string[] args)
- {
- IEnumerable<DateTime> times = GetTimes();
- foreach (var step in times.StepWise())
- {
- while (condition)
- {
- step.MoveNext();
- }
- Console.WriteLine(step.Current);
- }
- }
- public static class EnumerableExtension
- {
- public static IEnumerable<Step<T>> StepWise<T>(this IEnumerable<T> instance)
- {
- using (IEnumerator<T> enumerator = instance.GetEnumerator())
- {
- while (enumerator.MoveNext())
- {
- yield return new Step<T>(enumerator);
- }
- }
- }
- public struct Step<T>
- {
- private IEnumerator<T> enumerator;
- public Step(IEnumerator<T> enumerator)
- {
- this.enumerator = enumerator;
- }
- public bool MoveNext()
- {
- return enumerator.MoveNext();
- }
- public T Current
- {
- get { return enumerator.Current; }
- }
- }
- }
- public static IEnumerable<T> FunkyIEnumerable<T>(this Func<Tuple<bool, T>> nextOrNot)
- {
- while(true)
- {
- var result = nextOrNot();
- if(result.Item1)
- yield return result.Item2;
- else
- break;
- }
- yield break;
- }
- Func<Tuple<bool, int>> nextNumber = () =>
- Tuple.Create(SomeRemoteService.CanIContinueToSendNumbers(), 1);
- foreach(var justGonnaBeOne in nextNumber.FunkyIEnumerable())
- Console.Writeline(justGonnaBeOne.ToString());