Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the index of an object in a For Each...Next loop?

Tags:

vb.net

I'm using the following syntax to loop through a list collection:

For Each PropertyActor As JCPropertyActor In MyProperty.PropertyActors

    i = IndexOf(PropertyActor)
Next

How do I get the index of the current object within the loop? I'm using IndexOf(PropertyActor) but this seems inefficient as it searches the collection when I already have the object available!

like image 644
Simon Avatar asked Oct 15 '08 19:10

Simon


People also ask

Can we get index in for of loop?

Using enumerate() method to access index enumerate() is mostly used in for loops where it is used to get the index along with the corresponding element over the given range.

Can we get index in foreach JS?

Get The Current Array Index in JavaScript forEach()forEach(function callback(v) { console. log(v); }); The first parameter to the callback is the array value. The 2nd parameter is the array index.


4 Answers

An index doesn't have any meaning to an IEnumerable, which is what the foreach construct uses. That's important because foreach may not enumerate in index order, if your particular collection type implements IEnumerable in an odd way. If you have an object that can be accessed by index and you care about the index during an iteration, then you're better off just using a traditional for loop:

for (int i=0;i<MyProperty.PropertyActors.Length;i++)
{
    //...
}
like image 128
Joel Coehoorn Avatar answered Oct 17 '22 02:10

Joel Coehoorn


AFAIK since this pulls the object out of the collection, you would have to go back to the collection to find it.

If you need the index, rather than using a for each loop, I would just use a for loop that went through the indices so you know what you have.

like image 40
Mitchel Sellers Avatar answered Oct 17 '22 02:10

Mitchel Sellers


It might be easiest to just keep a separate counter:

i = 0
For Each PropertyActor As JCPropertyActor In MyProperty.PropertyActors
    ...
    i = i + 1
Next

As an aside, Python has a convenient way of doing this:

for i, x in enumerate(a):
    print "object at index ", i, " is ", x
like image 32
Greg Hewgill Avatar answered Oct 17 '22 01:10

Greg Hewgill


just initialize an integer variable before entering the loop and iterate it...

Dim i as Integer 
For Each PropertyActor As JCPropertyActor In MyProperty.PropertyActors
    i++
Next
like image 29
sebagomez Avatar answered Oct 17 '22 00:10

sebagomez