Created
January 19, 2022 23:18
-
-
Save okyrylchuk/adfa5d47e2a8faa9730cc9be268a7ba6 to your computer and use it in GitHub Desktop.
Extensions GetEnumerator for foreach loops with Range type
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
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