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

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

    I don't believe there is a way to get the value of the current iteration of a foreach loop. Counting yourself, seems to be the best way.

    May I ask, why you would want to know?

    It seems that you would most likley be doing one of three things:

    1) Getting the object from the collection, but in this case you already have it.

    2) Counting the objects for later post processing...the collections have a Count property that you could make use of.

    3) Setting a property on the object based on its order in the loop...although you could easily be setting that when you added the object to the collection.

提交回复
热议问题