Logo

Programming-Idioms

History of Idiom 7 > diff from v118 to v119

Edit summary for version 119 by programming-idioms.org:
[C#] +DemoURL

Version 118

2021-09-27, 16:19:40

Version 119

2021-10-02, 15:32:02

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;
Imports
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++);
        }
    }
}
Code
foreach (var (i, x) in items.AsIndexed())
{
    System.Console.WriteLine($"{i}: {x}");
}

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

Such an extension method isn't provided as part of the standard framework but can be added to a project
Demo URL
https://sharplab.io/#gist:3ed90ef3cdcf1d00bb8c2f152eec6612