Home > Mobile >  csvHelper sort dynamic data
csvHelper sort dynamic data

Time:03-28

Can anyone help me to understand how we can sort data in csvHelper before we write to string object? I am trying with Key but it is not working in case when there is dynamic data.

        string source = "James,Anthony,Mary\n,10,\n21,,212";



        using var reader = new StringReader(source);
        using var csvReader = new CsvReader(reader, CultureInfo.InvariantCulture);
        var records =  csvReader.GetRecords<dynamic>().ToList();


        var orderedRecords = records.OrderBy(r => r.Key);

        using (var writer = new StringWriter())
        using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
        {
            csv.WriteRecords(orderedRecords);

            Console.WriteLine( writer.ToString());
        }

I am getting following exception.

CsvHelper.WriterException: 'An unexpected error occurred.
  IWriter state:
  Row: 1
  Index: 0
  HeaderRecord:
  1
  '

The expected output I am looking for is,

   Anthony,James,Mary //--> Header Sorted Alphabetically
   ,10,               //--> First Row Sorted as per Header
   21,,212            //--> Second Row Sorted As Per Header

I appreciate your help on this.

CodePudding user response:

After updating the question. You need to use James, Antony or Mary instead of 'Key' to sort data and the code works:

var source = $"James,Anthony,Mary\n,10,\n21,,212";

using var reader = new StringReader(source);
using var csvReader = new CsvReader(reader, CultureInfo.InvariantCulture);
var records = csvReader.GetRecords<dynamic>().ToList();

var orderedRecords = records.OrderBy(r => r.James);

using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.WriteRecords(orderedRecords);

    Console.WriteLine(writer.ToString());
}

P.S. It's very dangerous when you use dynamic to read data, usually we use stable data table.

  • Related