Skip to content

Type Conversion

Paul Joiner edited this page Aug 4, 2021 · 4 revisions

💡 Note: This feature requires version 0.6.0 of the library or newer.

The data in a field of an IRow object can be converted from a string to a type using one of the following generic Convert methods. Remember to including the DwC_A.Extensions namespace to use this feature.

T Convert<T>(string term)
T Convert<T>(int index)
object Convert(string term, Type type)
object Convert(int index, Type type)
T? ConvertNullable<T>(string term)
T? ConvertNullable<T>(int index)
ConvertResult TryConvert<T>(string term, out T value) 
ConvertResult TryConvert<T>(int index, out T value)
ConvertResult TryConvertNullable<T>(string term, out T? value) 
ConvertResult TryConvertNullable<T>(int index, out T? value) 

The Convert and ConvertNullable overloads will throw on parsing errors and the TryConvert overloads will return a ConvertResult that indicates whether conversion was successful or not and a message indicating the type of error that occurred. ConvertResult implements the bool operator so that it can be used in the idiomatic way of TryParse without examining the ConvertResult properties directly.

if( row.TryConvert<DateTime>(Terms.eventDate, out DateTime eventDate) )
{
    //Use eventDate here
}

ConvertResult can be used to log parsing errors which is helpful in troubleshooting issues with file data. For example, if processing a data file where decimalLatitude may be null the missing rows may be logged as follows.

using DwC_A.Extensions;
using DwC_A.Terms;

var archive = new ArchiveReader(fileName);
var occurrence = archive.CoreFile;

occurrence.DataRows
    .Select((row, index) => new {index, row})
    .ToList()
    .ForEach(indexedRow => {
        var result = indexedRow.row.TryConvert<double>(Terms.decimalLatitude, out double decimalLatitude);
        if(!result) 
            Console.WriteLine( $"Row {indexedRow.index}: id: {indexedRow.row["id"]} failed with error {result.Message}" );

        //Process data here
        //...
    })

/*
Log or Console output
Row 4477: 2542790964 failed with error Term http://rs.tdwg.org/dwc/terms/decimalLatitude with value (null) could not be converted to type System.Double
Row 4478: 2542790947 failed with error Term http://rs.tdwg.org/dwc/terms/decimalLatitude with value (null) could not be converted to type System.Double
Row 4479: 2542790821 failed with error Term http://rs.tdwg.org/dwc/terms/decimalLatitude with value (null) could not be converted to type System.Double
*/

Note: Row index values are zero based and may be off by one if there are header rows in the file.