2D Array. Set all values to specific value

LINQ doesn't work particularly well with multi-dimensional arrays.

Jagged arrays aren't too bad:

var array = Enumerable.Range(0, 10)
                      .Select(x => Enumerable.Repeat('x', 10).ToArray())
                      .ToArray();

... but rectangular arrays don't have any specific support. Just use loops.

(Note the use of Enumerable.Repeat as a somewhat simpler approach to creating the 1-dimensional array, btw.)


One way you could do this is like so:

// Define a little function that just returns an IEnumerable with the given value
static IEnumerable<int> Fill(int value)
{
    while (true) yield return value;
}

// Start with a 1 dimensional array and then for each element create a new array 10 long with the value of 2 in
var ar = new int[20].Select(a => Fill(2).Take(10).ToArray()).ToArray();

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);

Well, this might be cheating because it simply moves the looping code to an extension method, but it does allow you to initialize your 2D array to a single value simply, and in a fashion similar to how you can initialize a 1D array to a single value.

First, as Jon Skeet mentioned, you could clean up your example of initializing a 1D array like this:

int [] numbers = Enumerable.Repeat(1,20).ToArray();

With my extension method, you will be able to initialize a 2D array like this:

public static T[,] To2DArray<T>(this IEnumerable<T> items, int rows, int columns)
{
    var matrix = new T[rows, columns];
    int row = 0;
    int column = 0;

    foreach (T item in items)
    {
        matrix[row, column] = item;
        ++column;
        if (column == columns)
        {
            ++row;
            column = 0;
        }
    }

    return matrix;
}

Tags:

C#

.Net