新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

c#中如何用foreach获取index,foreach语句c#

发布时间:2024-03-26 18:33:07

c#中如何用foreach获得index

在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来存储当前元素的索引,并在每次循环中递增该变量。这样就能够获得每一个元素的索引并进行相应的操作。