How do you get the index of the current iteration of a foreach loop?

后端 未结 30 1725
刺人心
刺人心 2020-11-22 07:05

Is there some rare language construct I haven\'t encountered (like the few I\'ve learned recently, some on Stack Overflow) in C# to get a value representing the current iter

30条回答
  •  攒了一身酷
    2020-11-22 07:20

    Using @FlySwat's answer, I came up with this solution:

    //var list = new List { 1, 2, 3, 4, 5, 6 }; // Your sample collection
    
    var listEnumerator = list.GetEnumerator(); // Get enumerator
    
    for (var i = 0; listEnumerator.MoveNext() == true; i++)
    {
      int currentItem = listEnumerator.Current; // Get current item.
      //Console.WriteLine("At index {0}, item is {1}", i, currentItem); // Do as you wish with i and  currentItem
    }
    

    You get the enumerator using GetEnumerator and then you loop using a for loop. However, the trick is to make the loop's condition listEnumerator.MoveNext() == true.

    Since the MoveNext method of an enumerator returns true if there is a next element and it can be accessed, making that the loop condition makes the loop stop when we run out of elements to iterate over.

提交回复
热议问题