WebI greatly prefer using a for loop in this situation compared to tracking the index with a local variable. Finally C#7 has a decent syntax for getting an index inside of a foreach loop (i. e. tuples): foreach (var (item, index) in collection.WithIndex()) { Debug.WriteLine($"{index}: {item}"); } A little extension method would be needed: WebWhen you are processing a collection or an array of values within a foreach loop, it is a simple task to determine the index of the item being worked with during the current iteration. You can declare a variable outside of the loop and initialise it with the first index value, which is usually zero.
cforeach用法输出字符串(c#编程:从键盘输入一个字符串, …
WebOct 7, 2024 · User281315223 posted. Obviously, a simple for-loop would be better suited for a situation like this, however you can use the IndexOf() method within your loop to actually determine the index of the current item that is being iterated over : foreach(var item in testList) { //This will yield the proper index that you are currently on int index = … WebApr 11, 2024 · It allows // an instance of the class to be used in a foreach statement. public IEnumerator GetEnumerator() { for (int index = top - 1; index >= 0; index--) { yield return values [index]; } } IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator (); } public IEnumerable TopToBottom { get { return this; } } public IEnumerable BottomToTop … shoveit hand safety tool
C# tip: how to get the index of an item in a foreach …
WebJun 8, 2024 · How to get the index of the current element in a foreach loop? The easiest way is to store and update the index in a separate variable List myFriends = new List { "Emma", "Rupert", … WebFind current index in a foreach loop in C# This post will discuss how to find the index of the current iteration in a foreach loop in C#. The LINQ’s Select () method projects each element of a sequence into a new form by incorporating the element’s index. WebSep 20, 2024 · Luckily, there are several ways to get an index variable with foreach: Declare an integer variable before the loop, and then increase that one inside the loop … shovel 241