Skip to content

Instantly share code, notes, and snippets.

@Zodt
Last active October 3, 2022 05:32
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zodt/09c484c224f8a8bd11d96fe3ab962904 to your computer and use it in GitHub Desktop.
Save Zodt/09c484c224f8a8bd11d96fe3ab962904 to your computer and use it in GitHub Desktop.
C# Enumerate like in python through Extensions class
// 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