How can I determine if I’m in the final loop of a For Each statement in VB.NET?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The generally, collections on which you can perform
For Eachon implement theIEnumeratorinterface. This interface has only two methods,MoveNextandResetand one property,Current.Basically, when you use a
For Eachon a collection, it calls theMoveNextfunction and reads the value returned. If the value returned isTrue, it means there is a valid element in the collection and element is returned via theCurrentproperty. If there are no more elements in the collection, theMoveNextfunction returnsFalseand the iteration is exited.From the above explanation, it is clear that the
For Eachdoes not track the current position in the collection and so the answer to your question is a short No.If, however, you still desire to know if you’re on the last element in your collection, you can try the following code. It checks (using LINQ) if the current item is the last item.
It is important to know that calling
Last()on a collection will enumerate the entire collection. It is therefore not recommended to callLast()on the following types of collections:For such collections, it is better to get an enumerator for the collection (via the
GetEnumerator()function) so you can keep track of the items yourself. Below is a sample implementation via an extension method that yields the index of the item, as well as whether the current item is the first or last item in the collection.Here is a sample usage:
Output
Index Value IsFirst IsLast ----- ----- ------- ------ 0 0 True False 1 1 False False 2 1 False False 3 2 False False 4 3 False False 5 5 False False 6 8 False False 7 13 False False 8 21 False False 9 34 False False 10 55 False False 11 89 False True