C# newbie: find out the index in a foreach block
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
for(int i = 0; i < y.Count; i++)
{
}
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.
Contrary to a few other answers, I would be perfectly happy to mix foreach
with a counter (as per the code in the question). This retains your ability to use IEnumerable[<T>]
rather than requiring an indexer.
But if you want, in LINQ:
foreach (var pair in y.Select((x,i) => new {Index = i,Value=x})) {
Console.WriteLine(pair.Index + ": " + pair.Value);
}
(the counter approach in the question is a lot simpler and more effecient, but the above should map better to a few scenarios like Parallel.ForEach).
No, there's no implicit "counter" inside a foreach loop, really.
What the foreach loop does behind the covers is create an IEnumerator and then loop over the items one by one, calling the .MoveNext() method on the IEnumerator interface.
There's (unfortunately?) no counter variable exposed on the IEnumerator interface - only .Reset() and .MoveNext() methods and a Current
property (returning the current item)
Marc
链接地址: http://www.djcxy.com/p/52980.html上一篇: C#如何获得上次在foreach语句?