Manually increment an enumerator inside foreach loop

前端 未结 8 1053
情话喂你
情话喂你 2021-01-18 06:20

I have a nested while loop inside a foreach loop where I would like to advance the enumerator indefinitately while a certain condition is met. To do this I try casting the e

8条回答
  •  暖寄归人
    2021-01-18 06:54

    You could use a func as your iterator and keep the state that you are changing in that delegate to be evaluated each iteration.

    public static IEnumerable FunkyIEnumerable(this Func> nextOrNot)
        {
            while(true)
            {
               var result = nextOrNot();
    
                if(result.Item1)
                    yield return result.Item2;
    
                else
                    break;
    
            }
    
            yield break;
    
        }
    
        Func> nextNumber = () => 
                Tuple.Create(SomeRemoteService.CanIContinueToSendNumbers(), 1);
    
        foreach(var justGonnaBeOne in nextNumber.FunkyIEnumerable())
                Console.Writeline(justGonnaBeOne.ToString());
    

提交回复
热议问题