Skip to content

Instantly share code, notes, and snippets.

@gabriel-vanca
Forked from Ninjanaut/foreach-with-index.md
Last active September 14, 2024 17:46
Show Gist options
  • Save gabriel-vanca/f39eebfe75c2cadb8c8b94866e98cbe7 to your computer and use it in GitHub Desktop.
Save gabriel-vanca/f39eebfe75c2cadb8c8b94866e98cbe7 to your computer and use it in GitHub Desktop.
C#_foreach-with-index
using System.Collections.Generic;
using System.Linq;

namespace Utility.Extensions
{
    public static class IEnumerableExtensions
    {
        public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> self)
            => self?.Select((item, index) => (item, index)) ?? new List<(T, int)>();
    }
}
foreach (var (item, index) in collection.WithIndex())
{
    Debug.WriteLine($"{index}: {item}");
}

Requires C# 7.0 or higher

Source: https://stackoverflow.com/a/39997157

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment