Skip to content

Instantly share code, notes, and snippets.

@jcbozonier
Created March 20, 2009 19:05
Show Gist options
  • Select an option

  • Save jcbozonier/82515 to your computer and use it in GitHub Desktop.

Select an option

Save jcbozonier/82515 to your computer and use it in GitHub Desktop.
/*
Stole this concept from Python. IMO it helps reduce clutter
in non-performance optimized loops. No dealing with incrementing
or setting the same condition time after time.
*/
/// Incrementing usage example:
foreach(var i in A.Range(0,10))
{
Print(i);
}
// Prints out: 0123456789
/// End of example.
/// Decrementing usage example:
foreach(var i in A.Range(10,0))
{
DoSomething(i);
}
// Prints out: 9876543210
/// End of example.
public static class MyList
{
/// <summary>
/// Lazily creates a list of numbers that span
/// a given range. The greater number is
/// excluded and the smaller is included.
/// For ex.
///
/// For Range(0,3) the output is {0,1,2}
/// For Range(3,0) the output is {2,1,0}
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
/// <returns></returns>
public static IEnumerable<int> Range(int start, int end)
{
if (start < end)
for (var i = start; i < end; i++)
{
yield return i;
}
else
for (var i = end - 1; i >= start; i--)
{
yield return i;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment