Reputation: 449
I have a class that I'm writing to a CSV file like this:
csvWriter.Configuration.RegisterClassMap(new AffidavitFullAndPartialMapping(detailLevel));
csvWriter.WriteRecords(allAffidavits);
After I send that "allAffidavits" collection to be written, I want to manually write one more row to the CSV. This last row will be all blank spaces, except for the last cell needs to contain a specific value.
So I thought I'd do something described in the official CsvHelper documentation (in a section called "Writing individual fields"):
You can also write each field manually if you like.
var csv = new CsvWriter( textWriter ); foreach( var item in list ) { csv.WriteField( "a" ); csv.WriteField( 2 ); csv.WriteField( true ); csv.NextRecord(); }
But how can I know how many blank cells to manually write? This is the same number as columns that are already in my CSV file. Due to the mapping (see first line of code at the top of this post) it may vary dynamically.
Thanks,
Eliezer
Upvotes: 0
Views: 2010
Reputation: 23383
You could loop through all the property and reference maps and count them. It's possible to set a higher index, so it would probably be better to find the highest index instead. There is an internal method that should probably be made public that you could use for this.
internal int GetMaxIndex()
{
if( PropertyMaps.Count == 0 && ReferenceMaps.Count == 0 )
{
return -1;
}
var indexes = new List<int>();
if( PropertyMaps.Count > 0 )
{
indexes.Add( PropertyMaps.Max( pm => pm.Data.Index ) );
}
indexes.AddRange( ReferenceMaps.Select( referenceMap => referenceMap.GetMaxIndex() ) );
return indexes.Max();
}
For now just copy this. If it works for you, submit a ticket in GitHub to have this method made public.
Upvotes: 1
Reputation: 449
Josh, thank you very much for your solution. Since posting my original question, I thought of something similar.
I replaced the two lines I had above:
csvWriter.Configuration.RegisterClassMap(new AffidavitFullAndPartialMapping(detailLevel));
csvWriter.WriteRecords(allAffidavits);
with this:
var classMapping = new AffidavitFullAndPartialMapping(detailLevel);
csvWriter.Configuration.RegisterClassMap(classMapping);
csvWriter.WriteRecords(allAffidavits);
I was then able to get the number of columns in the CSV:
int numberOfColumnsInCsv = classMapping.PropertyMaps.Count;
And in a loop - iterating that many times - execute this:
csvWriter.WriteField(string.Empty);
Upvotes: 0