Skip to content

Instantly share code, notes, and snippets.

@Ninjanaut
Created November 1, 2021 10:41
Show Gist options
  • Save Ninjanaut/0352e7d3afd14fc2ff3fc935b0a6a0a3 to your computer and use it in GitHub Desktop.
Save Ninjanaut/0352e7d3afd14fc2ff3fc935b0a6a0a3 to your computer and use it in GitHub Desktop.
foreach-with-index
using System.Collections.Generic;
using System.Linq;

namespace Web.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}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment