Csvhelper: Map multiple values from .csv file into one property field

Created on 29 Oct 2012  路  8Comments  路  Source: JoshClose/CsvHelper

Hello,

is there a way to map, for e.g., two values (from two different fields) from .csv file into one property field?
e.g
Map(m => m.UserAddress).Name("StreetName"_someDelimiter_"StreetNumber");

Most helpful comment

This is done as is available on NuGet as version 1.10.0. https://github.com/JoshClose/CsvHelper/commit/8255adf57798a0846c46a2edb44a086e9f550324

All 8 comments

No, there is no way to do that.

One thing you could do is create a property for StreetName and StreetNumber and have those properties alter the UserAddress value when they're set.

You could also set the property by hand, which isn't much more code.

C# var myObjects = new List<MyObject>(); while( csvReader.Read() != null ) { var myObject = csvReader.GetRecord<MyObject>(); myObject.UserAddress = csvReader.GetField( "StreetName" ) + " " + csvReader.GetField( "StreetNumber" ); myObjects.Add( myObject ); }

I did this from the top of my head, so I don't know if it compiles. ;)

It compiles :), I've already done this way, but wondering if there is another way (because of importing data from csv files with different structure, one have Address field, the other StreetName + StreetNumber).
Thanks for quick response!

I could possibly build in some sort of support for this. I'm thinking more along the lines of how the constructor mapping works. i.e.

``` C#
ConstructUsing( () => new MyObject() );

I might be something like this:

``` C#
Map( m => m.UserAddress ).ConvertUsing( ( string[] row ) => row[0] + " " + row[4] );

More than likely the current row wouldn't get passed in; it would be some object that gave you access to the readers GetField and GetRecord type methods.

Would this work?

It would be ok only if I can access to some field from row by Name (for e.g., row.Name("FieldName")), not by Index, because I don't know their order in .csv file. Is it possible?

Yes, it would be more like this:

C# Map( m => m.UserAddress ).ConvertUsing( ICsvRow row => row.GetField( "StreetAddress" ) + " " + row.GetField( "StreeNumber" ) );

This does not exist yet. I'm just talking about what I could possibly add. :)

It would be nice. And again, thanks a lot!

No problem. I will look into doing this in the next week or so here.

This is done as is available on NuGet as version 1.10.0. https://github.com/JoshClose/CsvHelper/commit/8255adf57798a0846c46a2edb44a086e9f550324

Was this page helpful?
0 / 5 - 0 ratings

Related issues

NeilMeredith picture NeilMeredith  路  4Comments

marcselman picture marcselman  路  4Comments

JoshClose picture JoshClose  路  5Comments

malinru picture malinru  路  5Comments

DmitryEfimenko picture DmitryEfimenko  路  3Comments