Skip to content

Instantly share code, notes, and snippets.

@chilversc
Created May 24, 2013 12:49
Show Gist options
  • Save chilversc/5643278 to your computer and use it in GitHub Desktop.
Save chilversc/5643278 to your computer and use it in GitHub Desktop.
Specify field order for CsvHelper when writing
static void WriteCsv<T> (IEnumerable<T> data, string file, params string[] fields)
{
var writerType = typeof (CsvWriter);
var writerParam = Expression.Parameter (writerType, "writer");
var itemType = typeof (T);
var itemParam = Expression.Parameter (itemType, "item");
var fieldWriters = new List<Action<CsvWriter, T>> ();
foreach (var name in fields) {
var value = Expression.PropertyOrField (itemParam, name);
var writeMethod = Expression.Call (writerParam, "WriteField", new[] {value.Type}, value);
var action = Expression.Lambda<Action<CsvWriter, T>> (writeMethod, writerParam, itemParam).Compile ();
fieldWriters.Add (action);
}
using (var stream = new StreamWriter (file))
using (var writer = new CsvWriter (stream)) {
foreach (var name in fields) {
writer.WriteField (name);
}
writer.NextRecord ();
foreach (var item in data) {
foreach (var write in fieldWriters) {
write (writer, item);
}
writer.NextRecord ();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment