Is it possible to do start iterating from an element other than the first using foreach?

后端 未结 5 1885
花落未央
花落未央 2020-12-05 01:26

I\'m thinking about implementing IEnumerable for my custom collection (a tree) so I can use foreach to traverse my tree. However as far as I know foreach always starts from

5条回答
  •  萌比男神i
    2020-12-05 02:21

    It's easiest to use the Skip method in LINQ to Objects for this, to skip a given number of elements:

    foreach (var value in sequence.Skip(1)) // Skips just one value
    {
        ...
    }
    

    Obviously just change 1 for any other value to skip a different number of elements...

    Similarly you can use Take to limit the number of elements which are returned.

    You can read more about both of these (and the related SkipWhile and TakeWhile methods) in my Edulinq blog series.

提交回复
热议问题