Skip to content

Instantly share code, notes, and snippets.

@okyrylchuk
Created January 19, 2022 23:18
Show Gist options
  • Save okyrylchuk/adfa5d47e2a8faa9730cc9be268a7ba6 to your computer and use it in GitHub Desktop.
Save okyrylchuk/adfa5d47e2a8faa9730cc9be268a7ba6 to your computer and use it in GitHub Desktop.
Extensions GetEnumerator for foreach loops with Range type
foreach (int i in 3..5)
{
Console.WriteLine(i);
}
foreach (int i in ..3)
{
Console.WriteLine(i);
}
foreach (int i in ^3..)
{
Console.WriteLine(i);
}
public static class GetEnumeratorExtenstions
{
public static IEnumerator<int> GetEnumerator(this Range range)
{
if (range.Start.IsFromEnd)
{
for (int i = range.Start.Value; i >= range.End.Value; i--)
{
yield return i;
}
}
else
{
for (int i = range.Start.Value; i <= range.End.Value; i++)
{
yield return i;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment