Assume an array:
double[,] array = new double[x,y];
I know that the elements will be initialised to zero but I want to set every one of the array to a 'double.NaN'.
I did initially try a foreach loop, but the compiler complained. The only other way is two nested 'for' loops acting with x and y. Is there an easier way?
SimonPosted Apr 26, 2009, 4:07 AM
Nope, doesn't work for me...
I cannot find anything on the 'net or in msdn/help/microsoft/books that allows you to set a multi dimensioned array to one value in one line of code...I'll just have to write two 'for' loops :(
SimonPosted Apr 17, 2009, 5:57 PM
Stefan - that is so simple why didn't I think of that...!
Thank you for your time and efforts - very appreciated :)
StefanPosted Apr 17, 2009, 5:38 PM
I figured out how to do this in a foreach loop. Here's how:
int[,] array = new int[2, 3];
foreach (int index in array)
{
array[index, index] = 10;
}
When I tested this, I added each array object to a list box. When I ran the app, the list box displayed the each object in the array, all set to 10.
Hope this helps!
SimonPosted Apr 17, 2009, 4:26 PM
This compiles and runs properly...
#include
"stdafx.h"#include
int
_tmain(int argc, _TCHAR* argv[]){
float b[2][2] = {4.5}; for(int i = 0; i < 2; i++) for(int j = 0; j < 2; j++)std::cout <<
"\t" << b[i,j]; return 0;}
I appreciate your help Stefan - thank you!
StefanPosted Apr 17, 2009, 3:24 PM
SimonPosted Apr 17, 2009, 11:06 AM
No, not quite. What I was after is that in C++ you can do this:
float SomeArray[1000] = {9.5f};
And this sets all 1000 elements to the value of 9.5. What I would like to find out is if I can set a C# array in an equally easy manner - as the alternatives are either clumsy or not allowed by the compiler e.g.
double [,] SomeArray = new double[x,y];
for( int i = 0; i < x; i++)
for( int j = 0; j < y; j++)
SomeArray[i,j] = double.NaN;
This is just clumsy in comparison to C++, whereas the code below isn't allowed:
foreach (var a in double)
{
a = double.NaN;
}
What am I missing...?!
StefanPosted Apr 16, 2009, 5:51 PM
If so, you would do something like this:
int [,] rectangularArray =
{
{0, 1, 2} {3, 4, 5}, {6, 7, 8}, {9, 10, 11}
};
This creates an array, implies the size of the rows and columns, and initializes the values. To read the values, however, you still need the nested for loops.
I hope this is what you were looking for. If not, please post back.