I'm using CsvHelper to read a CSV file.
This is my code (pretty simple):
using (var reader = new StreamReader("example.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
var records = csv.GetRecords<CsvData>();
int i = 0;
foreach (var record in records)
{
i ;
Console.WriteLine($"Processed {i}/{records.Count()} records.");
}
}
Console.WriteLine("Script finished");
The problem is that my code is not looping that foreach, so it won't print anything... I put a breakpoint in i ;
line but it doesn't breaks.
If I print records.Count()
it will return 3:
This could be an example of a CSV file:
Code format so you can copy it:
Size,Color
8,Yellow
2,Orange
13,Blue
And this could be an example of class CsvData:
public class CsvData
{
public decimal? Size { get; set; }
public string Color { get; set; }
}
How should I iterate my rows parsing into my CsvData class creating a List<CsvData>
or similar?
CodePudding user response:
@Joel Coehoorn is correct. As soon as you call .Count()
, you have just told CsvHelper
to read the whole CSV file in order to find out how many records there are in the file. You are now at the end of the data stream and there are no more records left to read. Calling .ToList()
does the same thing. It reads the whole CSV file, but this time it saves the records to memory in the records
variable. This is fine if your file is smaller, but you could run into memory issues if you have a very large file.
Just by:
List<CsvData> records = csv.GetRecords<CsvData>().ToList();