Convert a 1-d array of double to a single string

I wish to convert a 1-d array of double into a single string with each element of the array separated by a comma in the string.

I know I could create a loop an convert each element from a double to a string and store each result into a string array....then use String.Join (like below) to make the single string...but I was wanted to know if there is method to avoid a looping Thanks.

String.Join(",",stringarray)



Answer this question

Convert a 1-d array of double to a single string

  • danni123

    hi, jim

    Actually, whatever syntax you prefer to use, the perform of this algorithm is similar. String.Join only somewhat make the code short and simple, because the string class is a very commonly used class. And double type doesn't implement such a method. It's not the problem.

    BR



  • mmonte

    Well, I'd use:



    foreach(double dbl in d)
    {
    sb.AppendFormat("{0},", dbl);
    }

    but that's purely personal preference.

    However, the other change I'd suggest is in removing the finall comma. That could be done with a simple:

    sb.Length --;



  • Creation

    Looping isn't an issue... but the fact that strings are immutable is (when you append to a string, a new string is created)

    The StringBuilder class overcomes this issue.

    ...assuming double[] d

    StringBuilder sb = new StringBuilder(/* estimate total length in characters*/)

    for(int i = 0; i < d.Length; i++)

    {

    sb.AppendFormat("{0}," dIdea.ToString("000.0"));

    }

    sb.Remove(sb.Length-1,1); // remove last comma... not sure if the indexes are right

    string s = sb.ToString();


  • Convert a 1-d array of double to a single string