Alex Rivera | Logout

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

Asked 2008-12-17T23:26:36.790
28

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

Edit
Report

3 Answers

2

Short answer: You can't

Long answer: There's nothing in the semantics of a For Each statement that allows you to identify whether you're running the first, last or any particular iteration.

For Each is built in the IEnumerable and IEnumerable<> interfaces, and the behavior is dependent on the implementation you're calling. It's valid, though confusing, for the collection you're iterating to return elements in a different order every time. Fortunately, List<> doesn't do this.

If you really need to know that a particular iteration is the last, you could identify the last element (in advance) and then take different action when you encounter that element.

Easier would be to detect the first iteration (say, through a boolean) and then do something different.

An example (C#, but the VB will be similar):

StringBuilder result = new StringBuilder();
bool firstTime = true;
foreach(string s in names)
{
    if (!firstTime)
    {
        result.Append(", ");
    }

    result.Append(s);
    firstTime = false;
}
answered 2008-12-17T23:41:21.330
1

I keep coming back to this post, so I decided to sit down and think about this issue and I came up with this:

    For Each obj In myCollection
        Console.WriteLine("current object: {0}", obj.ToString)

        If Object.ReferenceEquals(obj, myCollection.Last()) Then
            Console.WriteLine("current object is the last object")
        End If
    Next

You could even reduce the If...Then...End If statement to a single line if you wanted to. I'm not sure if calling .Last() on every iteration has a large impact on performance, but you can always assign it to a variable outside of the loop if that's what keeps you awake at night.

answered 2013-02-27T21:25:57.703
0

Well there are few workaround Suppose you are working with CheckBoxList

Then this code sample might help :

Dim count As Integer = 0
Dim totalListCount As Integer = CheckBoxList.Items.Count()
For Each li In CheckBoxList.Items
         count += 1
           // This is the Last Item
      If count = totalListCount THEN
          // DO Somthing.....
      END IF
NEXT     
answered 2012-07-25T13:54:08.540

Your Answer