Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you find the last loop in a For Each (VB.NET)?

How can I determine if I'm in the final loop of a For Each statement in VB.NET?

like image 556
RichC Avatar asked Dec 17 '08 23:12

RichC


People also ask

What is for each loop in VB net?

In the VB.NET, For Each loop is used to iterate block of statements in an array or collection objects. Using For Each loop, we can easily work with collection objects such as lists, arrays, etc., to execute each element of an array or in a collection.

How do you write a for loop in Visual Basic?

In VB.NET, when we write one For loop inside the body of another For Next loop, it is called Nested For Next loop. Syntax: For variable_name As [Data Type] = start To end [ Step step ] For variable_name As [Data Type] = start To end [ Step step ]

Do While loop in VB net example?

If the condition is true, the next iteration will be executed till the condition become false. Example 1. Write a simple program to print a number from 1 to 10 using the Do While loop in VB.NET. In the above program, the Do While loop executes the body until the given condition becomes false.

How is a foreach statement different from a for statement?

foreach is useful when iterating all of the items in a collection. for is useful when iterating overall or a subset of items. The foreach iteration variable which provides each collection item, is READ-ONLY, so we can't modify the items as they are iterated. Using the for syntax, we can modify the items as needed.


2 Answers

The generally, collections on which you can perform For Each on implement the IEnumerator interface. This interface has only two methods, MoveNext and Reset and one property, Current.

Basically, when you use a For Each on a collection, it calls the MoveNext function and reads the value returned. If the value returned is True, it means there is a valid element in the collection and element is returned via the Current property. If there are no more elements in the collection, the MoveNext function returns False and the iteration is exited.

From the above explanation, it is clear that the For Each does 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.

For Each item in Collection     If item Is Collection.Last Then         'do something with your last item'     End If Next 

It is important to know that calling Last() on a collection will enumerate the entire collection. It is therefore not recommended to call Last() on the following types of collections:

  • Streaming collections
  • Computationally expensive collections
  • Collections with high tendency for mutation

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.

<Extension()> Public Iterator Function EnumerateEx(Of T)(collection As IEnumerable(Of T))     As IEnumerable(Of (value As T, index As Integer, isFirst As Boolean, isLast As Boolean))      Using e = collection.GetEnumerator()         Dim index = -1         Dim toYield As T          If e.MoveNext() Then             index += 1             toYield = e.Current         End If          While e.MoveNext()             Yield (toYield, index, index = 0, False)             index += 1             toYield = e.Current         End While          Yield (toYield, index, index = 0, True)     End Using End Function 

Here is a sample usage:

Sub Main()     Console.WriteLine("Index   Value   IsFirst   IsLast")     Console.WriteLine("-----   -----   -------   ------")      Dim fibonacci = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89}      For Each i In fibonacci.EnumerateEx()         Console.WriteLine(String.Join("   ", $"{i.index,5}",                                              $"{i.value,5}",                                              $"{i.isFirst,-7}",                                              $"{i.isLast,-6}"))     Next      Console.ReadLine() End Sub 

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
like image 83
Alex Essilfie Avatar answered Oct 11 '22 10:10

Alex Essilfie


It probably would be easier to just use a For loop instead of ForEach. But, similarly, you could keep a counter inside your ForEach loop and see if its equal to yourCollection.Count - 1, then you are in the last iteration.

like image 30
Strelok Avatar answered Oct 11 '22 10:10

Strelok