CsvHelper
CsvHelper copied to clipboard
Writing multiple fields from a single property
Possibly by adding ConvertUsing functionality to writer.
https://github.com/JoshClose/CsvHelper/issues/392
Bummer, I just tried the following and it only took the last mapping.
Map(m => m.ApplicantDob).Name("Applicant_birth_day").TypeConverter<DateTimeDayTypeConverter>();
Map(m => m.ApplicantDob).Name("Applicant_birth_month").TypeConverter<DateTimeMonthTypeConverter>();
Map(m => m.ApplicantDob).Name("Applicant_birth_year").TypeConverter<DateTimeYearTypeConverter>();
+1. I'm having to modify my model to return pieces of a DateTime (similar to what roryprimrose is trynig to do). It'd be great if this kind of functionality was built in.
This already works actually. Notice the false being passed into the Map call.
[TestClass]
public class MultipleFieldsFromOnePropertyTests
{
[TestMethod]
public void WriteMultipleFieldsFromSinglePropertyTest()
{
using( var stream = new MemoryStream() )
using( var reader = new StreamReader( stream ) )
using( var writer = new StreamWriter( stream ) )
using( var csv = new CsvWriter( writer ) )
{
var records = new List<Test>
{
new Test { Dob = DateTime.Now }
};
csv.Configuration.RegisterClassMap<TestMap>();
csv.WriteRecords( records );
writer.Flush();
stream.Position = 0;
Console.WriteLine( reader.ReadToEnd() );
}
}
private class Test
{
public DateTime Dob { get; set; }
}
private sealed class TestMap : CsvClassMap<Test>
{
public TestMap()
{
Map( m => m.Dob, false ).Name( "A" );
Map( m => m.Dob, false ).Name( "B" );
Map( m => m.Dob, false ).Name( "C" );
}
}
}
Output:
A,B,C
9/6/2017 6:21:56 PM,9/6/2017 6:21:56 PM,9/6/2017 6:21:56 PM