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.
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
Because a and b and c , so it's name is C. C came out of Ken Thompson's Unix project at AT&T. He originally wrote Unix in assembly language. He wrote a language in assembly called B that ran on Unix, and was a subset of an existing language called BCPL.
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 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.
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