How to get the index of the current iteration of a foreach loop in C#?
Hello everyone! I'm a beginner in C# and I've encountered a problem when working with the foreach loop. I need to get the index of the current element being processed in the loop.
Here's an example of my code:
```csharp
List fruits = new List { "apple", "banana", "orange", "pear" };
foreach (string fruit in fruits)
{
// I need to output the element number and its name
// For example: "Element 1: apple"
Console.WriteLine($"Element ?: {fruit}");
}
```
I know that in a for loop you can use a variable i that increments on each iteration. But in foreach there is no such variable by default. I tried creating my own counter variable before the loop and incrementing it inside, but that seems like a workaround and not very convenient.
Please tell me, is there a built-in way in C# to get the i
No answers yet.
Log in to leave an answer
Blogs
TypeScript vs Python for Backend: What to Choose in 2024