public static string Format(string format, Array matrix, IMatrixFormatProvider formatProvider)
{
// Initial argument checking
if (matrix.Rank > 2)
{
throw new NotSupportedException("Matrices with more than two dimensions are not supported.");
}
// Try to parse the format options passed through the "format" argument
string newline, elementFormat;
if (!parseOptions(format, out newline, out elementFormat))
{
throw new FormatException(String.Format("The format of '{0}' is invalid.", format));
}
IFormatProvider culture = formatProvider.InnerProvider;
// Retrieve matrix dimensions. If the matrix is a jagged array,
// we will compute the columns for each of the rows.
int rows = matrix.GetLength(0);
int cols = (matrix.Rank == 2) ? matrix.GetLength(1) : 0;
// Initialize the matrix construction
StringBuilder sb = new StringBuilder();
sb.Append(formatProvider.FormatMatrixStart);
// For each row
for (int i = 0; i < rows; i++)
{
// Start constructing the row
sb.Append(formatProvider.FormatRowStart);
// Construct the columns for the row
if (matrix.Rank == 1)
{
Object obj = matrix.GetValue(i);
Array row = obj as Array;
if (row == null)
{
sb.Append(handleOtherFormats(elementFormat, obj, culture));
}
else
{
#region Process row for jagged arrays
cols = row.Length;
// For each column
for (int j = 0; j < cols; j++)
{
sb.Append(handleOtherFormats(elementFormat, row.GetValue(j), culture));
if (j < cols - 1) sb.Append(formatProvider.FormatColDelimiter);
}
#endregion
}
}
else
{
#region Process row for multidimensional arrays
// For each column
for (int j = 0; j < cols; j++)
{
sb.Append(handleOtherFormats(elementFormat, matrix.GetValue(i, j), culture));
if (j < cols - 1) sb.Append(formatProvider.FormatColDelimiter);
}
#endregion
}
// Finalize constructing the row
sb.Append(formatProvider.FormatRowEnd);
// Check if we are still in the middle of the row
if (i < rows - 1) sb.Append(formatProvider.FormatRowDelimiter);
}
// Finalize constructing the matrix
sb.Append(formatProvider.FormatMatrixEnd);
// Finally, perform post-processing such as replacing user
// selected newlines or presenting the output in just one line.
String str = sb.ToString();
str = str.Replace("\n", newline);
if (String.IsNullOrEmpty(newline))
str = Regex.Replace(str, " +", " ");
return str;
}