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

Solution 1:

Yes. Do the following:

Collection<string> myCollection = new Collection<string>;

foreach (string curString in myCollection.Skip(3))
    //Dostuff

Skip is an IEnumerable function that skips however many you specify starting at the current index. On the other hand, if you wanted to use only the first three you would use .Take:

foreach (string curString in myCollection.Take(3))

These can even be paired together, so if you only wanted the 4-6 items you could do:

foreach (string curString in myCollection.Skip(3).Take(3))

Solution 2:

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.

Solution 3:

You can use Enumerable.Skip to skip some elements, and have it start there.

For example:

foreach(item in theTree.Skip(9))  // Skips the first 9 items
{
    // Do something

However, if you're writing a tree, you might want to provide a member on the tree item itself that will return a new IEnumerable<T> which will enumerate from there down. This would, potentially, be more useful in the long run.