Created
November 13, 2022 17:31
-
-
Save spooky/15e425470d95b2c566680d20a8468f41 to your computer and use it in GitHub Desktop.
Read csv using Sylvan.Data.Csv
We can make this file beautiful and searchable if this error is corrected: No commas found in this CSV file in line 0.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
A;1;test;2022-11-11 | |
B;something;else | |
A;2;test2;2022-11-12 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Diagnostics; | |
using Sylvan.Data.Csv; | |
var options = new CsvDataReaderOptions { HasHeaders = false, Delimiter = ';' }; | |
using var csv = await CsvDataReader.CreateAsync("demo.csv", options); | |
var sw = Stopwatch.StartNew(); | |
while(await csv.ReadAsync()) | |
{ | |
var type = csv.GetString(0); | |
object? row = type switch { | |
"A" => CreateRecordA(csv), | |
"B" => CreateRecordB(csv), | |
_ => throw new InvalidOperationException($"Unknown record type '{type}'"), | |
}; | |
Console.WriteLine(row); | |
} | |
sw.Stop(); | |
Console.WriteLine($"Time taken: {sw.Elapsed}"); | |
RecordA CreateRecordA(CsvDataReader csv) => new RecordA | |
{ | |
Id = csv.GetInt32(1), | |
Name = csv.GetString(2), | |
Date = csv.GetDateTime(3), | |
}; | |
RecordB CreateRecordB(CsvDataReader csv) => new RecordB | |
{ | |
Name = csv.GetString(1), | |
Description = csv.GetString(2), | |
}; | |
public record struct RecordA | |
{ | |
public int Id; | |
public string? Name; | |
public DateTime Date; | |
public override string ToString() => $"[{nameof(RecordA)}] {Id};{Name};{Date}"; | |
} | |
public record struct RecordB | |
{ | |
public string? Name; | |
public string? Description; | |
public override string ToString() => $"[{nameof(RecordB)}] {Name};{Description}"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment