CsvHelper icon indicating copy to clipboard operation
CsvHelper copied to clipboard

Writing multiple fields from a single property

Open JoshClose opened this issue 11 years ago • 3 comments

Possibly by adding ConvertUsing functionality to writer.

https://github.com/JoshClose/CsvHelper/issues/392

JoshClose avatar Sep 08 '15 20:09 JoshClose

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>();

roryprimrose avatar Oct 02 '15 05:10 roryprimrose

+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.

necoras avatar Nov 04 '15 18:11 necoras

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

JoshClose avatar Sep 06 '17 23:09 JoshClose