Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an "upto" method in C#?

Tags:

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#?

like image 403
dharmatech Avatar asked Nov 17 '11 08:11

dharmatech


2 Answers

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.

like image 176
George Duckett Avatar answered Sep 20 '22 18:09

George Duckett


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.

like image 44
Ian Mercer Avatar answered Sep 17 '22 18:09

Ian Mercer