Logo

Programming-Idioms

History of Idiom 7 > diff from v119 to v120

Edit summary for version 120 by Anonymous:
New C# implementation by user [Anonymous]

Version 119

2021-10-02, 15:32:02

Version 120

2021-10-05, 18:28:28

Idiom #7 Iterate over list indexes and values

Print each index i with its value x from an array-like collection items

Idiom #7 Iterate over list indexes and values

Print each index i with its value x from an array-like collection items

Variables
i,x,items
Variables
i,x,items
Extra Keywords
indices traverse traversal
Extra Keywords
indices traverse traversal
Imports
using System.Linq;
Code
foreach (var (x, i) in items.Select((x, i)=>(x, i)))
{
    System.Console.WriteLine($"{i}: {x}");
}
Comments bubble
System.Linq provides Select(), which allows access to the index.

Note: order is item, index, and not the conventional index, item.
Doc URL
https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=netframework-4.0
Origin
https://stackoverflow.com/questions/43021/how-do-you-get-the-index-of-the-current-iteration-of-a-foreach-loop
Demo URL
https://sharplab.io/#v2:C4LgTgrgdgNAJiA1AHwAIAYAEqCMA6AGQEsoBHAbgFgAoDbHAFiupoDcBDMTI4AUwFsAzpgC8mKLwDumYoOAAeXOgB8AbwBE7dTEzqARtt0BjdQF9mNAGYB7ML3ZGAFpgAUHLi4AeOogEpuUNx8QngAyrwANrxGwC5ePr4iyvHcvmk0qjSY2fR4uACcLgAk6qpEpiCYqp6m6r7MpjRAA