温馨提示×

c#中怎么用foreach获取index

c#
小亿
117
2024-03-26 18:33:07
栏目: 编程语言

在C#中,可以使用foreach结合ListCount属性和IndexOf方法来获取元素的索引。示例代码如下:

List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };

int index = 0;
foreach (int number in numbers)
{
    Console.WriteLine($"Index: {index}, Number: {number}");
    index++;
}

在上面的代码中,我们首先定义一个包含整数的列表numbers,然后使用foreach循环遍历列表中的元素。在循环内部,我们使用一个变量index来存储当前元素的索引,并在每次循环中递增该变量。这样就可以获取每个元素的索引并进行相应的操作。

0