Let say I got this function :
void int Calculate(double[] array) {}
And in my main I got this array:
double[,] myArray = new double[3,3];
How can I call Calculate(…) ?
I try (that’s don’t compile) :
double[] mySingleArray = myArray[0];
What I want to avoid is unnecessary loop (for).
I declare a regular array, but if a jagged array or any other type of array works better, it’s fine for me.
I use c# 3.5
First, let’s declare your Calculate() method like this:
Don’t worry, you can still pass an array to that code. You might also need
IList<double>, but 9 times out of 10 the IEnumerable is good enough. The main thing is that this will let us use theyieldkeyword to slice up your array in an efficient way:It still needs some work because it only works with rank 2 arrays, but it should be fine for the example you posted.
Now you can call your calculate function like this:
Note that due to the way IEnumerable and the yield statement work the for loop in the code I posted is essentially free. It won’t run until you actually iterate the items in your Calculate method, and even there runs in a ‘just-in-time’ fashion so that the whole algorithm remains O(n).
It gets even more interesting when you share what your Calculate method is doing. You might be able to express it as a simple Aggregate + lambda expression. For example, let’s say your calculate method returned the number of items > 5:
Or say it summed all the items: