Here's a bit of code which prints out the squares of the numbers from 0 to 9:
for (int i = 0; i < 10; i++) Console.WriteLine(i*i);
Doing something from 0 to N by 1 via a for
loop is a very common idiom.
Here's an UpTo
method which expresses this:
class MathUtil { public static void UpTo(int n, Action<int> proc) { for (int i = 0; i < n; i++) proc(i); } }
The squares example above is now:
MathUtil.UpTo(10, (i) => Console.WriteLine(i * i));
My question is, does the standard C# library come with something like the above UpTo
?
Ideally, I'd like a way to have 'UpTo' be a method on all integer objects. So I could do:
var n = 10; n.UpTo(...);
Is this possible in C#?
Turn it into an extension method (note the this before the n
parameter, which defines the type this method operates on):
static class MathUtil { public static void UpTo(this int n, Action<int> proc) { for (int i = 0; i < n; i++) proc(i); } }
Usage:
10.UpTo((i) => Console.WriteLine(i * i));
Note: The above method call isn't particularly intuitive though. Remember code is written once and read many times.
Maybe allowing something like below might be slightly better, but to be honest i'd still just write a foreach
loop.
0.UpTo(10 /*or 9 maybe*/, (i) => Console.WriteLine(i * i));
If you wanted this, then you could write an extension method like this:
public static void UpTo(this int start, int end, Action<int> proc) { for (int i = start; i < end; i++) proc(i); }
Change <
to <=
if you want an inclusive upper bound.
Take a look at LINQ TakeWhile or for your specific case of integers, use Enumerable.Range
Enumerable.Range(1, 10).Select(i => ...);
Arguably you shouldn't be putting an Action on the end there, see comments on ForEach here.
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