Search code examples
c#csvhelper

csvhelper using tuple as records


Can I use tuples when writing to a csv file?

I am trying to reduce memory footprint by using tuple instead of a class instance.

The documentation does mention dynamic and anonymous types; but I don't see for value tuple. Also, how do I handle headers and custom formatting?


Solution

  • You can use WriteRecords with a ValueTuple. You just need to use @dbc's comment and set the MemberTypes in the CsvConfiguration to MemberTypes.Fields.

    void Main()
    {
        var rows = new (int Id, string Name, DateTime BornOn)[]
        {
            (1, "Jack", new DateTime(2000, 1, 1)),
            (2, "Jill", new DateTime(1990, 3, 13)),
            (3, "McDonald", new DateTime(1970, 5, 12)),
            (4, "Burger King", new DateTime(1880, 8, 22)),
            (5, "Colonel Sanders", new DateTime(1960, 6, 11)),
        };
        
        var config = new CsvConfiguration(CultureInfo.InvariantCulture)
        {
            MemberTypes = CsvHelper.Configuration.MemberTypes.Fields
        };
    
        //using (var writer = new StreamWriter("path\\to\\file.csv"))
        using (var csv = new CsvWriter(Console.Out, config))
        {
            csv.Context.RegisterClassMap<ValueTupleMap>();
            
            csv.WriteRecords(rows);
        }
    }
    
    public class ValueTupleMap : ClassMap<ValueTuple<int,string,DateTime>>
    {
        public ValueTupleMap()
        {
            Map(m => m.Item1).Name("#");
            Map(m => m.Item2).Name("Name");
            Map(m => m.Item3).Name("DoB");
        }
    }