Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D Array. Set all values to specific value

Tags:

c#

.net

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?

like image 542
Matan Shahar Avatar asked Mar 27 '12 16:03

Matan Shahar


1 Answers

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);
like image 105
Bob Avatar answered Oct 19 '22 08:10

Bob