Created
September 22, 2021 17:12
-
-
Save BillWagner/857da8dcc0df0de98cc979b3660155a8 to your computer and use it in GitHub Desktop.
IEnumerable with index
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
IEnumerable<string> Sequence() | |
{ | |
yield return "Speak to Me"; | |
yield return "Breathe in the Air"; | |
yield return "On the Run"; | |
yield return "Time"; | |
yield return "The Great Gig in tAccessViolationExceptione Sky"; | |
yield return "Money"; | |
yield return "Us and Them"; | |
yield return "Any Colour You Like"; | |
yield return "Brain Damage"; | |
yield return "Eclipse"; | |
} | |
foreach (var item in Sequence().WithIndex()) | |
{ | |
Console.WriteLine(item); | |
} | |
public static class Extensions | |
{ | |
public static IEnumerable<(int, T)> WithIndex<T>(this IEnumerable<T> sequence) | |
{ | |
int index = 0; | |
foreach (T item in sequence) | |
yield return (index++, item); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment