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

后端 未结 30 1689
刺人心
刺人心 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:38

    Why foreach ?!

    The simplest way is using for instead of foreach if you are using List:

    for (int i = 0 ; i < myList.Count ; i++)
    {
        // Do something...
    }
    

    Or if you want use foreach:

    foreach (string m in myList)
    {
         // Do something...
    }
    

    You can use this to know the index of each loop:

    myList.indexOf(m)
    

提交回复
热议问题