C# Program to Get the index of the Current Iteration of a foreach Loop Using Select() Method. The method Select() is a LINQ method. LINQ is a part of C# that is used to access different databases and data sources. The Select() method selects the value and index of the iteration of a foreach loop.
You can access the index even without using enumerate() . Using a for loop, iterate through the length of my_list . Loop variable index starts from 0 in this case. In each iteration, get the value of the list at the current index using the statement value = my_list[index] .
You can't, you either need to keep the index separately:
int index = 0;
for(Element song : question) {
System.out.println("Current index is: " + (index++));
}
or use a normal for loop:
for(int i = 0; i < question.length; i++) {
System.out.println("Current index is: " + i);
}
The reason is you can use the condensed for syntax to loop over any Iterable, and it's not guaranteed that the values actually have an "index"
In Java, you can't, as foreach was meant to hide the iterator. You must do the normal For loop in order to get the current iteration.
Keep track of your index: That's how it is done in Java:
int index = 0;
for (Element song: question){
// Do whatever
index++;
}
Not possible in Java.
Here's the Scala way:
val m = List(5, 4, 2, 89)
for((el, i) <- m.zipWithIndex)
println(el +" "+ i)
As others pointed out, 'not possible directly'. I am guessing that you want some kind of index key for Song? Just create another field (a member variable) in Element. Increment it when you add Song to the collection.
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