CsvHelper.GetRecords 返回时处理

CsvHelper.GetRecords disposed when returnin

我想从工作代码中提取方法。在这个函数中,我可以访问记录。但在返回时,记录的内容被处理掉。 因此,我尝试将 csv.GetRecords() 转换为列表,但出现错误消息,因为记录仅包含方法 Equals()、GetEnumerator()、GetHasCode()、GetType() 和 ToString()。 我快疯了:/ 有没有人可以帮助我?谢谢。

private static IEnumerable<Animal> LoadFromCsvFile(/*[ExistingFile]*/ string fileName, Encoding encodingFormat, char separator)
    {
        using (var reader = new StreamReader(fileName))
        using (var csv = new CsvReader(reader))
        {
            csv.Configuration.RegisterClassMap<AnimalClassMap>();
            csv.Configuration.Delimiter = separator.ToString(CultureInfo.InvariantCulture);
            csv.Configuration.Encoding = encodingFormat;
            IEnumerable<Animal> records = csv.GetRecords<Animal>();
            foreach (Animal rec in records)
            {
                Console.WriteLine($"{rec.FatherId}x{rec.MotherId} - {rec.Name} ({rec.Male}) breed {rec.Breed}");
            }

            return records;
        }
    }

GetRecords<Animal>() 没有立即获取记录。它会在您迭代记录时产生结果。当您在迭代它们之前 return records 时,您会发现 CsvReader 上下文已经被处理掉并且不能再 yield 结果。您可以通过在离开 using 语句之前使用 .ToList() 枚举所有记录来解决此问题。

IEnumerable<SccAnimal> records = csv.GetRecords<Animal>().ToList();

另一种选择是制作 LoadFromCsvFile : IDisposable 然后在 Dispose() 方法中处理 StreamReaderCsvReader 而不是将它们放在 using 中陈述。在这种情况下,您不会能够将它们迭代两次

CsvHelper Getting Started

The GetRecords method will return an IEnumerable that will yield records. What this means is that only a single record is returned at a time as you iterate the records. That also means that only a small portion of the file is read into memory.