Alex Rivera | Logout

CSV string handling

Asked 2008-08-07T05:49:04.253
21

Typical way of creating a CSV string (pseudocode):

  1. Create a CSV container object (like a StringBuilder in C#).
  2. Loop through the strings you want to add appending a comma after each one.
  3. After the loop, remove that last superfluous comma.

Code sample:

public string ReturnAsCSV(ContactList contactList)
{
    StringBuilder sb = new StringBuilder();
    foreach (Contact c in contactList)
    {
        sb.Append(c.Name + ",");
    }

    sb.Remove(sb.Length - 1, 1);
    //sb.Replace(",", "", sb.Length - 1, 1)

    return sb.ToString();
}

I like the idea of adding the comma by checking if the container is empty, but doesn't that mean more processing as it needs to check the length of the string on each occurrence?

I feel that there should be an easier/cleaner/more efficient way of removing that last comma. Any ideas?

Edit
Report

2 Answers

5

Don't forget our old friend "for". It's not as nice-looking as foreach but it has the advantage of being able to start at the second element.

public string ReturnAsCSV(ContactList contactList)
{
    if (contactList == null || contactList.Count == 0)
        return string.Empty;

    StringBuilder sb = new StringBuilder(contactList[0].Name);

    for (int i = 1; i < contactList.Count; i++)
    {
        sb.Append(",");
        sb.Append(contactList[i].Name);
    }

    return sb.ToString();
}

You could also wrap the second Append in an "if" that tests whether the Name property contains a double-quote or a comma, and if so, escape them appropriately.

answered 2008-08-07T12:00:51.553
1

Just a thought, but remember to handle comma's and quotation marks (") in the field values, otherwise your CSV file may break the consumers reader.

answered 2008-08-07T11:18:09.143

Your Answer