I have a foreach block where I want to plot out for trace-debug purposes the index of the step inside the foreach. As a C# newbie I do it as follows:
int i = 1;
foreach (x in y)
{
... do something ...
WriteDebug("Step: "+i.ToString());
i++;
}
I wondered if there’s any way to get the value of the current step’s index without explicitly creating a variable for that purpose.
EDIT: To clarify, I’m obviously familiar with the option of a for loop, however it’s not an array I’m going through but rather an unordered collection. The reason for the numbering is just for the purpose of showing progress in the debug level and nothing else.
No, there is not.
This is an instance where you’re better off using a basic for loop
rather than a for each loop
EDIT: In response to askers clarification.
If you’re iterating through an enumerator with no size property (such as length or count), then your approach is about as clear as you can get.
Second Edit
Given me druthers I’d take Marc’s answer using select to do this these days.