In C#, you can get the index of the current iteration of a foreach loop using a variable to keep track of the current index. Here's an example:
csharpvar items = new List<string>{"apple", "banana", "orange"};
foreach(var item in items)
{
int index = items.IndexOf(item);
Console.WriteLine($"Item at index {index}: {item}");
}
In the example above, we create a List of strings and iterate over it using a foreach loop. Inside the loop, we get the index of the current item using the IndexOf()
method of the List. We then print out the index and the item itself.
Note that this approach works only if the collection being iterated over supports the IndexOf()
method. If the collection does not support this method, you can use a separate variable to keep track of the current index, as shown in the example below:
csharpvar items = new string[]{"apple", "banana", "orange"};
for(int i = 0; i < items.Length; i++)
{
string item = items[i];
Console.WriteLine($"Item at index {i}: {item}");
}
In this example, we use a for loop instead of a foreach loop and keep track of the current index using the i
variable. We then use the i
variable to print out the index and the item at that index.
Comments
Post a Comment