I think the title is quite clear, so I'll just write some personal opinions here.
Consider a matrix of numbers, the equivalent representations in C# code are double[,]
and double[][]
respectively. When using multi-dimensional array (2D in this specific situation), It can be easily seen that one doesn't have to check either there is any null reference of double[]
or the size of rows are the same, which allows a better understanding of the core problem. Also it descirbes the matrix more accurately from my point of view, since in most cases a matrix should be treated as a single entity rather than a list of arrays.
But using multi-dimensional array may result in more lines of code. If one wants to apply math operations on it, say, transposition, he would have to use nested loops like
var row = mat.GetLength(0);
var col = mat.GetLength(1);
var newmat = new double[col, row];
for (var i = 0; i < row; i++)
{
for (var j = 0; j < col; j++)
{
newmat[j, i] = mat[i, j];
}
}
With jagged array, he can simply write
var newmat = Enumerable.Range(0, mat[0].Length - 1).
Select(i => mat.Select(r => r[i]).ToArray()).ToArray();
I'm not sure which one is better. Usually I only create my own subroutine unless there is no solution provided by .Net, so I prefer the latter. But multi-dimensional array do have its advantages which I really like. Could anyone teach me about how to choose between them?