I'm trying to think of clever, clear, and simple ways to write code that describes the sequence of integers in a given range.
Here's an example:
IEnumerable<int> EnumerateIntegerRange(int from, int to)
{
for (int i = from; i <= to; i++)
{
yield return i;
}
}
This is already in the framework: Enumerable.Range.
For other types, you might be interested in the range classes in my MiscUtil library.
Alternately, a fluent interface from extension methods:
public static IEnumerable<int> To(this int start, int end)
{
return start.To(end, i => i + 1);
}
public static IEnumerable<int> To(this int start, int end, Func<int, int> next)
{
int current = start;
while (current < end)
{
yield return current;
current = next(current);
}
}
used like:
1.To(100)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With