Reputation: 48558
I know that we can initialise an array in one of two ways:
Enumerable.Repeat
(Probably causes memory issues? Link: Enumerable.Repeat has some memory issues?)I have two questions:
Can we initialise an array using Array.ForEach
in this manner?
double[][] myarr = new double[13][];
Array.ForEach(myarr, *enter_code_here*);
I tried replacing enter_code_here
with:
s => s = new double[2];
but it does not initialise myarr
.
What are the other array initialisation methods without any memory issues?
Upvotes: 4
Views: 2445
Reputation: 1
This is how I created a 256 row x 2 column array and initialized all values to -1.
int[][] myArr = Enumerable.Range(0, 256).Select(i => new int[2] {-1, -1}).ToArray();
Upvotes: 0
Reputation: 437336
You can use Enumerable.Repeat
just fine to initialize any array. The only thing you need to be careful of is that if the array element is of a reference type there are two ways to go about it:
// #1: THIS ARRAY CONTAINS 10 REFERENCES TO THE SAME OBJECT
var myarr = Enumerable.Repeat(new object(), 10).ToArray();
// #2: THIS ARRAY CONTAINS REFERENCES TO 10 DIFFERENT OBJECTS
var myarr = Enumerable.Range(0, 10).Select(i => new object()).ToArray();
// #3: SAME RESULT AS #2 BUT WITH Enumerable.Repeat
var myarr = Enumerable.Repeat(0, 10).Select(i => new object()).ToArray();
Upvotes: 8
Reputation: 6293
A1: No, you can't. Foreach just executes method with element as parameter but don't modify elements.
A2: You can use the folowing method to resolve the issue
static T[][] CreateArray<T>(int rows, int cols)
{
T[][] array = new T[rows][];
for (int i = 0; i < array.GetLength(0); i++)
array[i] = new T[cols];
return array;
}
Upvotes: 3