csvHelper 排序动态数据
csvHelper sort dynamic data
任何人都可以帮助我了解我们如何在写入字符串对象之前对 csvHelper 中的数据进行排序吗?我正在尝试使用 Key,但在有动态数据的情况下它不起作用。
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());
}
我遇到以下异常。
CsvHelper.WriterException: 'An unexpected error occurred.
IWriter state:
Row: 1
Index: 0
HeaderRecord:
1
'
我正在寻找的预期输出是,
Anthony,James,Mary //--> Header Sorted Alphabetically
,10, //--> First Row Sorted as per Header
21,,212 //--> Second Row Sorted As Per Header
非常感谢你在这方面的帮助。
更新问题后。
您需要使用 James、Antony 或 Mary 而不是 'Key' 来对数据进行排序并且代码有效:
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。使用dynamic读取数据是非常危险的,一般我们使用stable data table.
任何人都可以帮助我了解我们如何在写入字符串对象之前对 csvHelper 中的数据进行排序吗?我正在尝试使用 Key,但在有动态数据的情况下它不起作用。
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());
}
我遇到以下异常。
CsvHelper.WriterException: 'An unexpected error occurred.
IWriter state:
Row: 1
Index: 0
HeaderRecord:
1
'
我正在寻找的预期输出是,
Anthony,James,Mary //--> Header Sorted Alphabetically
,10, //--> First Row Sorted as per Header
21,,212 //--> Second Row Sorted As Per Header
非常感谢你在这方面的帮助。
更新问题后。 您需要使用 James、Antony 或 Mary 而不是 'Key' 来对数据进行排序并且代码有效:
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。使用dynamic读取数据是非常危险的,一般我们使用stable data table.