If you wish to manipulate the "edge cells" of a 2 dimensional Array of objects of various Types, here's one strategy:
using System.Collections.Generic;
using System.Linq;
public void Set2DArrayValues<T>(ref T[,] theAry, Func<int, int, T> arrayValueSetter)
{
if (theAry == null) return;
if (xfunc == null) return;
int dim0 = theAry.GetLength(0);
if (dim0 == 0) return;
int dim1 = theAry.GetLength(1);
if (dim1 == 0) return;
for (int i = 0; i < dim0; i++)
{
for (int j = 0; j < dim1; j++)
{
theAry[i,j] = arrayValueSetter(i, j);
}
}
}
This a generic Method which gets passed a 2-dimensional Array of arbitrary Type (T), and a Func (Function) that takes two integer arguments, and returns an object of Type T.
Here's how you could use it to create a 6x6 Array of String with zeroes in all the "edge" cells, and the non-edge cells set to String.Empty:
private strAry[,];
private void SampleUsage()
{
strAry = new string[6,6];
int dim0 = strAry.GetLength(0) - 1;
int dim1 = strAry.GetLength(1) - 1;
Func<int, int, string> stringValueSetter = (i1, i2) =>
{
return (i1 == 0 || i1 == dim0 || i2 == 0 || i2 == dim1)
? "0"
: String.Empty;
};
Set2DArrayValues<string>(ref strAry, stringValueSetter);
}
Another example: if we had created an Integer 2-d array, and wanted the diagonals in the matrix to be the square of the matrix row number, and all other cells to be set to #0:
int[,] intAry = new int[6,6];
Set2DArrayValues<int>(ref intAry, (i1, i2) =>
{
return (i1 == i2)
? i1*i2
: 0;
});
Note that here we define the necessary Func (function) directly by using a lambda expression.
But, what if we want to do more than just "set" values; what if we'd like to transform
existing values in the Array? To do that requires only a minor modification to the above:
public void Transform2DArrayValues<T>(ref T[,] theAry, Func<T, int, int, T> xtfunc)
{
if (theAry == null) return;
if (xtfunc == null) return;
int dim0 = theAry.GetLength(0);
if (dim0 == 0) return;
int dim1 = theAry.GetLength(1);
if (dim1 == 0) return;
for (int i = 0; i < dim0; i++)
{
for (int j = 0; j < dim1; j++)
{
theAry[i, j] = xtfunc(theAry[i,j], i, j);
}
}
}
Now, the Func (function) we pass will contain the current value in the cell; we can use that in some way, or ignore it. For example:
int dim0 = 6;
int dim1 = 6;
string[,] strAry2 = new string[dim0,dim1];
strAry2[1, 2] = "Bacon";
strAry2[3, 4] = "Bacon";
Func<string, int, int, string> stringArrayValueTransform = (str, i1, i2) =>
{
if (str == "Bacon") return "Hamster";
if (i1 == 0) return "Bob";
if (i1%5 == 0)
return (i2%2 == 0)
? "OriginalGriff"
: "Sheep";
return "Vote this up :)";
};
Transform2DArrayValues(ref strAry2, stringArrayValueTransform);