Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSV string handling

Tags:

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?

like image 732
Christian Hagelid Avatar asked Aug 07 '08 05:08

Christian Hagelid


People also ask

How do I handle extra commas in a CSV file?

You need to specify text qualifiers. Generally a double quote (") is used as text qualifiers. All the text is always put inside it and all the commas inside a text qualifier is ignored. This is a standard method for all CSV, languages and all platforms for properly handling the text.

Is a CSV file just a string?

CSV is string data. If your data is normalized you can do things like attempt to convert to a numeric; if it works, it's a number, if it fails, it's a string. It will fail. I need to change the strings to their correct type.

What is CSV format example?

A CSV file is a list of data separated by commas. For instance, it may look like the following: Name,email,phone number,address. Example,[email protected],555-555-5555,Example Address.

How are CSV files formatted?

CSV , or Comma-separated Values, is an extremely common flat-file format that uses commas as a delimiter between values. Anyone familiar with spreadsheet programs has very likely encountered CSV files before - they're easily consumed by Google Spreadsheet, Microsoft Excel, and countless other applications.


1 Answers

You could use LINQ to Objects:

string [] strings = contactList.Select(c => c.Name).ToArray();
string csv = string.Join(",", strings);

Obviously that could all be done in one line, but it's a bit clearer on two.

like image 124
David Wengier Avatar answered Sep 30 '22 05:09

David Wengier