I am experiencing a strange issue occurring when I invoke the Count() method on a IEnumerable.
My code is simply reading a csv file using the CSV Helper package. I can loop through all the csv records and output the information of each record - until I attempt to get the count before the loop:
StreamReader streamReader = new(_fileName, Encoding.GetEncoding("iso-8859-1"));
CsvReader csvReader = new(streamReader, csvConfig);
IEnumerable<WebApi.Entities.Csv.Transaction> records = csvReader.GetRecords<WebApi.Entities.Csv.Transaction>();
System.Diagnostics.Debug.WriteLine($"CSV Record Count: {records.Count()}"); //this line gets the count
foreach (var record in records)
{
System.Diagnostics.Debug.WriteLine(record.Description);
}
When the count statement is present, the foreach loop never executes, it is as though the records var becomes empty after the count. If I remove the Count statement then the iterations over the loop occur without problems.
I also found that if I run the count statement twice, the first statements returns the count, but the second returns 0:
System.Diagnostics.Debug.WriteLine($"CSV Record Count: {records.Count()}"); // returns correct count
System.Diagnostics.Debug.WriteLine($"CSV Record Count: {records.Count()}"); // returns 0
What is going on here and how can I fix it?