Costa.Gustavo
Costa.Gustavo

Reputation: 849

CsvHelper: Save Map values ​to a variable

I'm trying to write a .csv file, where the DateTime ArrivalDate type field must be formatted according to the counterparty field, as I'm trying to do with the FormatDate function below. However, I can't save the counterparty value in a variable to be passed as a parameter to the function already mentioned.

public class FuturesFilesMapping : BaseTypeConfiguration<FuturesFilesModel>
    {
        public FuturesFilesMapping()
        {
            var counterparty = Map(i => i.Counterparty).Constant("counterparty");

            Map(i => i.TradeDate).Name("Trade Date").Index(1).TypeConverterOption.Format("dd/MM/yyyy");
            Map(i => i.BmfAccount).Name("A/C Ref").Index(2);
            Map(i => i.Side).Name("B/S").Index(3);
            Map(i => i.Quantity).Name("Lots").Index(4);
            Map(i => i.Strike).Name("Strike").Index(5);
            Map(i => i.Type).Name("Type").Index(6);
            Map(i => i.Payout).Name("Call/Put").Index(7);
            Map(i => i.Price).Name("Price").Index(8);
            Map(i => i.Ticker).Name("Ric").Index(9);
            Map(i => i.Broker).Name("Exec Firm Name").Index(10);
            Map(i => i.Counterparty).Name("Contraparte").Index(11);
            Map(i => i.Desk).Name("Mesa").Index(12);
            Map(i => i.Exchange).Name("Exchange").Index(13);
            Map(i => i.ArrivalDate, ).Name("delivery").Index(14).TypeConverterOption.Format(FormatDate(counterparty));
            Map(i => i.Currency).Name("Curr").Index(15);
            Map(i => i.ContractId).Name("Age").Index(16);
        }

        public static string FormatDate(string couterparty)
        {
            if (couterparty.Equals("FCM CITIGROUP GLOBAL MARKETS INC"))
            {
                return "MMM-yy";
            }
            else
            {
                return "dd MMM yyy";
            }
        }
    }

Could anyone tell me if I can perform this conditional formatting in the mapping class?

Upvotes: 3

Views: 167

Answers (1)

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30565

you can use TypeConverter

Map(m => m.ArrivalDate, ).Name("delivery").Index(14).TypeConverter<MyDateConverter>();

then

public class MyDateConverter : DefaultTypeConverter
{
    public override object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
    {
        if (row.GetField("Contraparte").Equals("FCM CITIGROUP GLOBAL MARKETS INC"))
            return DateTime.ParseExact(text, "MMM-yy", System.Globalization.CultureInfo.InvariantCulture) );

        return DateTime.ParseExact(text,  "dd MMM yyy", System.Globalization.CultureInfo.InvariantCulture) );
    }

    public override string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
    {
        throw new NotImplementedException();
    }
}

Upvotes: 1

Related Questions