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!
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.
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.
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++)
{
//...
}
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With