[C#] CSV Object Extension

1 minute read

This is a simple extension that generates a CSV string out of any object. Let me explain a little bit of how it works:

1. First, create some objects

var dean = new Person 
{ 
    Id = 1, 
    Name = "Dean", 
    Birthdate = new DateTime(1979, 01, 24),
    Deathdate = new DateTime(2025, 01, 01)
};
var sam = new Person 
{ 
    Id = 2, 
    Name = "Sam", 
    Birthdate = new DateTime(1983, 05, 02),
    Deathdate = new DateTime(2050, 01, 01)
};

2. Now let's try using it

String basic = dean.ToCSV();

The output of this would be:

    Id,Name,Birthdate
    1,Dean,1979-01-24

3. Providing options for formatting

String list = new List<Person> { dean, sam }
    .ToCSV(separator: ";", surroundByQuotes: true, datesFormat: "dd/MM/yyyy");

And this is what it looks like:

    "Id";"Name";"Birthdate";"Deathdate"
    "1";"Dean";"24/01/1979";"01/01/2025"
    "2";"Sam";"02/05/1983";"01/01/2050"

4. Going specific

String verySpecificCSV = new List<Person> { dean, sam }
    .ToCSV(formattedProperties = {
        birthdate = "dd/MM/yyyy",
        deathdate = "yyyy MM dd"
    },
    translatedColumns = {
        Birthdate = "Nascimento",
        Deathdate = "Óbito"
    });

With these options, this would be the output:

    Id,Name,Nascimento,Óbito
    1,Dean,24/01/1979,2025 01 01
    2,Sam,02/05/1983,2050 01 01

Available options

type option description
object formattedProperties specific formats for specific properties - higher priority over other options
String separator separator character between cells
bool suppressHeader hide header or not
object translatedColumns replace column header names
List ignoredProperties remove columns
String datesFormat format all dates this way
bool surroundWithQuotes surround all cells with quotes
List surroundedWithQuotes surround specific cells with quotes

For more details, source at Github

Updated: