To assign specific value to 1D array I'm using LINQ like so:
int[] nums = new int[20];
nums = (from i in nums select 1).ToArray<int>();
nums[0] = 2;
There is similar way to do so in 2D ([x,y]) array? Or short way, without using nested loops?
If you really want to avoid nested loops you can use just one loop:
int[,] nums = new int[x,y];
for (int i=0;i<x*y;i++) nums[i%x,i/x]=n;
You can make it easier by throwing it into some function in a utility class:
public static T[,] GetNew2DArray<T>(int x, int y, T initialValue)
{
T[,] nums = new T[x, y];
for (int i = 0; i < x * y; i++) nums[i % x, i / x] = initialValue;
return nums;
}
And use it like this:
int[,] nums = GetNew2DArray(5, 20, 1);
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