Monday, February 04, 2008
« Seattle Code Camp: xUnit.net | Main | Comma Delimited String From An Array usi... »

Creating a comma delimited string from an array came up yesterday, here is a couple of methods, one from our junior developer and one that I did.  I entitled mine old school, because of the C coding that shaped my programming.

static internal String Junior(String[] list)
{
    String output = String.Empty;

    foreach (String item in list)
    {
        output += item + ",";
    }

    output.TrimEnd(',');

    return (output);
}

static internal String OldSchool(String[] list)
{
    StringBuilder output = new StringBuilder();

    foreach (String item in list)
    {
        if (String.IsNullOrEmpty(item))
            continue;

        if (output.Length > 0)
            output.Append(",");

        output.Append(item);
    }

    return (output.ToString());
}

Which one do you like?

{6230289B-5BEE-409e-932A-2F01FA407A92}

 

 

C# | Wayne
Thursday, February 07, 2008 2:04:12 PM (Pacific Standard Time, UTC-08:00)
You're likely to find better performance by just calling string.Join since that method was designed to do just what you're doing here. String.Join takes advantage of the internal string API (ex. fast string allocation, unsafe char buffers) to quickly put together a string with a given delimiter.
James Arendt
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Live Comment Preview