Logo

Programming-Idioms

History of Idiom 7 > diff from v115 to v116

Edit summary for version 116 by DavidArno:
New C# implementation by user [DavidArno]

Version 115

2021-09-06, 08:16:02

Version 116

2021-09-27, 09:39:27

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;
using System.Collections.Generic;
Code
foreach (var (item, index) in items.AsIndexed())
{
    Console.WriteLine($"{index}: {item}");
}

// ---------------------------------------------------------------
public static class Extensions
{
    public static IEnumerable<(T, int)> AsIndexed<T>(
        this IEnumerable<T> source)
    {
        var index = 0;
        foreach (var item in source)
        {
            yield return (item, index++);
        }
    }
}
Comments bubble
By adding a simple extension method to IEnumerable<T>, we can perform a simple foreach over the collection.

Such an extension method isn't provided as part of the standard framework but can be easily added to a project
Demo URL
https://sharplab.io/#v2:EYLgtghglgdgNAFxAJwK7wCYgNQB8ACATAIwCwAUPgAwAE+xALANwUUBuEyNUCApmAGcaAXhoxeAdxoAZKAIQAeWAgB8NAN40qcGsR16ahHQGYdAVh0AOfacMHjDcxZqWAnDQC+LchQBmAe2ReCABjAAsaAAoOLkiefh1YDF4ADwBKbhhuPkEAOgBBAQBJGGSU3gxItLSKdQoaBrpiV0iAEgAidSTUjxAN