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;
}
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.
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