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?
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... }
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.
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.
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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With