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()
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();
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;
}
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.)
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);
You can create a simple method that loops over all elements and initializes them:
public static void Fill2DArray<T>(T[,] arr, T value)
{
int numRows = arr.GetLength(0);
int numCols = arr.GetLength(1);
for (int i = 0; i < numRows; ++i)
{
for (int j = 0; j < numCols; ++j)
{
arr[i, j] = value;
}
}
}
This uses the same syntax as Array.Fill and will work for an array of any type
May I suggest a new extension method.
public static class TwoDArrayExtensions
{
public static void ClearTo(this int[,] a, int val)
{
for (int i=a.GetLowerBound(0); i <= a.GetUpperBound(0); i++)
{
for (int j=a.GetLowerBound(1); j <= a.GetUpperBound(1); j++)
{
a[i,j] = val;
}
}
}
}
Use it like this:
var nums = new int[10, 10];
nums.ClearTo(1);