csv change order of the columns

Viewed 435

I am currently using ServiceStack.Text to serialize CSV from a list of objects. I have a model:

public class UploadDocument
{

[DataMember(Name = "Patient")]
public string Patient { get; set; }

[DataMember(Name = "Patient First Name")]
public string PatientFirstName { get; set; }

[DataMember(Name = "Patient Last Name")]
public string PatientLastName { get; set; }

[DataMember(Name = "Email")]
public string Email { get; set; }

}

The result is:

Patient,    Patient First Name, Patient Last Name,  Email
XXX,        YYY,                ZZZZZ,              nwerwer@yahoo.com,    
XXX,        YYY,                ZZZZZ,              nwerwerwe@yahoo.com,    
XXX,        YYY,                ZZZZZ,              nwerwe@yahoo.com,   

However, for another report I need to change the order of the csv and return:

Email,               Patient,    Patient First Name, Patient Last Name,  
nwerwer@yahoo.com,   XXX,        YYY,                ZZZZZ,                  
nwerwerwe@yahoo.com, XXX,        YYY,                ZZZZZ,                  
nwerwe@yahoo.com,    XXX,        YYY,                ZZZZZ, 

Is there a way to do that avoiding create a new model?

2 Answers

There's some examples of setting Custom Headers in CustomHeaderTests.cs where you can override the CSV Headers that are serialized. Note: this is static configuration that should be initialized once on Startup as it's not ThreadSafe to mutate at runtime.

But I'd personally define a separate model with the order and number of headers you want, you shouldn't think of it as duplicating code, your declaratively defining the structure you want in each use-case which is more maintainable then modifying serialization implementation at runtime.

To map between the models you can use ServiceStack's AutoMapping Utils, e.g:

var report2 = report1.ConvertTo<List<Report2Document>>();

Another solution that avoids defining a model is to convert the model to an Object Dictionary, covert each dictionary into a List<KeyValuePair<string,string>> in the order that you want and serialize that.

Related