Home > Software engineering >  Column sortorder when writing CSV file using CsvHelper
Column sortorder when writing CSV file using CsvHelper

Time:05-18

When writing TSVs from .Net objects file using CsvHelper, I would like to control column sort order using attributes. When using the CsvHelper-provided Index(..) attribute, I am able to control serialization order, but the column header is suffixed with an index:

Model(s), inherited:

    /// <summary>
    /// Generic daily data
    /// </summary>
    public class DailyData
    {
        /// <summary>
        /// 
        /// </summary>
        [CsvHelper.Configuration.Attributes.Index(-2, -2)]
        public int IdDay {get;set;}
    }

    /// <summary>
    /// Generic hou-on-a-day data
    /// </summary>
    public class HourlyData : DailyData
    {
        /// <summary>
        /// 
        /// </summary>
        [CsvHelper.Configuration.Attributes.Index(-1)]
        public byte IdHour { get; set; }
    }

    /// <summary>
    /// 
    /// </summary>
    public class HourlyWeatherInfo : HourlyData
    {
        /// <summary>
        /// 
        /// </summary>
        public double Temperature { get; internal set; }
    }

Output:

IdDay1  IdHour1 Temperature
20220516    18  291.7
20220516    21  289.55
20220517    0   287.3
20220517    3   286.33

Am I overlooking functionality?

CodePudding user response:

It feels a bit hacky, but this seems to work.

    /// <summary>
    /// Generic daily data
    /// </summary>
    public class DailyData
    {
        /// <summary>
        /// 
        /// </summary>
        [CsvHelper.Configuration.Attributes.Index(-2,-3)]
        public int IdDay {get;set;}
    }

    /// <summary>
    /// Generic hou-on-a-day data
    /// </summary>
    public class HourlyData : DailyData
    {
        /// <summary>
        /// 
        /// </summary>
        [CsvHelper.Configuration.Attributes.Index(-1,-2)]
        public byte IdHour { get; set; }
    }

    /// <summary>
    /// 
    /// </summary>
    public class HourlyWeatherInfo : HourlyData
    {
        /// <summary>
        /// 
        /// </summary>
        public double Temperature { get; internal set; }
    }
  • Related