Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 the first element of the collection. I would like to choose from which element foreach starts. Is it possible to somehow change the element from which foreach starts?

like image 518
inferno Avatar asked Jun 21 '11 17:06

inferno


People also ask

How do you skip elements in foreach loop?

From the PHP manual: break ends execution of the current for, foreach, while, do-while or switch structure. break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. foreach ( $array as $value ) { if ( $value == 3 ) continue; # Skips # Code goes here... }

How do I find my last foreach iteration?

Use count() to determine the total length of an array. The iteration of the counter was placed at the bottom of the foreach() loop - $x++; to execute the condition to get the first item. To get the last item, check if the $x is equal to the total length of the array. If true , then it gets the last item.

Can you iterate array by using foreach loop How?

The forEach() method calls a specified callback function once for every element it iterates over inside an array. Just like other array iterators such as map and filter , the callback function can take in three parameters: The current element: This is the item in the array which is currently being iterated over.


2 Answers

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)) 
like image 145
MoarCodePlz Avatar answered Sep 29 '22 09:09

MoarCodePlz


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.

like image 45
Jon Skeet Avatar answered Sep 29 '22 10:09

Jon Skeet