Last active
October 3, 2022 05:32
-
-
Save Zodt/09c484c224f8a8bd11d96fe3ab962904 to your computer and use it in GitHub Desktop.
C# Enumerate like in python through Extensions class
This file contains hidden or 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
// C#9 | |
using System; | |
using System.Collections.Generic; | |
foreach (var (value, index) in 5..10) | |
{ | |
Console.WriteLine($"Value = {value.ToString()}, Index = {index.ToString()}"); | |
} | |
public static class RangeExtensions | |
{ | |
public static IEnumerator<ValueTuple<int, Index>> GetEnumerator(this Range range) | |
{ | |
if (range.Start.Value == range.End.Value) | |
throw new ArgumentOutOfRangeException(nameof(range), | |
"The initial value of the Range should not be equal to the final one"); | |
int index = default; | |
var enumerator = new RangeEnumerator(range); | |
for (var value = range.Start.Value; enumerator.Condition(value); enumerator.Expression(ref value)) | |
yield return (value, index++); | |
} | |
private readonly struct RangeEnumerator | |
{ | |
private readonly Range _range; | |
public RangeEnumerator(Range range) => _range = range; | |
private T GetResult<T>(T result, T revertResult) => _range.Start.Value > _range.End.Value ? revertResult : result; | |
internal void Expression(ref int value) => value = GetResult(++value, --value); | |
internal bool Condition(int value) => GetResult(value < _range.End.Value, value > _range.End.Value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment