Is there a better way to convert two-dimentional array to string? For logging purposes, I need to output a double[,] to the log file. So I need to represent the array as a string.

The following code gets the job done using basic C# 1 features, but I was wondering if there is a more elegant solution using Linq:

private static string OneRowPerLine(double[,] numbers)
{
    var ret = new StringBuilder();
    for(var i=numbers.GetLowerBound(0);i&lt;=numbers.GetUpperBound(0);i++)
    {
        for (var j = numbers.GetLowerBound(1); j &lt;= numbers.GetUpperBound(1); j++)
        {
            if(j&gt;numbers.GetLowerBound(1))
            {
                ret.Append(",");
            }
            ret.Append(numbers[i, j]);
        }
        ret.Append(Environment.NewLine);
    }
    return ret.ToString();
}
First off, I think there may be bugs in your code. Specifically in the dimension parameters of some of the GetLowerBound() parameters. Based on a quick glance, it should be:

private static string OneRowPerLine(double[,] numbers)
{
    var ret = new StringBuilder();
    for(var i=numbers.GetLowerBound(0);i&lt;=numbers.GetUpperBound(0);i++)
    {
        for (var j = numbers.GetLowerBound(1); j &lt;= numbers.GetUpperBound(1); j++)
        {
            if(j&gt;numbers.GetLowerBound(1))
            {
                ret.Append(",");
            }
            ret.Append(numbers[i, j]);
        }
        ret.Append(Environment.NewLine);
    }
    return ret.ToString();
}


I'll update this answer in a moment with some enhancements, but wanted to get this bit out of the way.

EDIT: here's a pair of methods which will do it a little more generically and without LINQ. It does employ generics (&lt;T&gt;) and extension methods (this), one of which is an iterator (yield return):

    private static string OneRowPerLine&lt;T&gt;(this T[,] numbers)
    {
        return string.Join(Environment.NewLine, numbers.FormatOneRow());
    }

    private static IEnumerable&lt;string&gt; FormatOneRow&lt;T&gt;(this T[,] numbers)
    {
        for (var i = numbers.GetLowerBound(0); i &lt;= numbers.GetUpperBound(0); i++)
        {
            var row = new T[numbers.GetLength(1)];

            for (var j = numbers.GetLowerBound(1); j &lt;= numbers.GetUpperBound(1); j++)
            {
                row[j] = numbers[i, j];
            }

            yield return string.Join(",", row);
        }
    }


call like this:

    double[,] stuff = {{1,2}, {3,4}, {5,6}};
    Console.WriteLine(stuff.OneRowPerLine());