Manually increment an enumerator inside foreach loop

前端 未结 8 1108
情话喂你
情话喂你 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 07:02

    This is just a guess, but it sounds like what you're trying to do is take a list of datetimes and move past all of them which meet a certain criteria, then perform an action on the rest of the list. If that's what you're trying to do, you probably want something like SkipWhile() from System.Linq. For example, the following code takes a series of datetimes and skips past all of them which are before the cutoff date; then it prints out the remaining datetimes:

    var times = new List()
        {
            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();
    

    Is that the sort of thing you're trying to do?

提交回复
热议问题