Skip to content

Instantly share code, notes, and snippets.

@yzorg
Last active April 4, 2023 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yzorg/9a450311f445ec14d71dac2d723cb7c1 to your computer and use it in GitHub Desktop.
Save yzorg/9a450311f445ec14d71dac2d723cb7c1 to your computer and use it in GitHub Desktop.
For counting CSV rows. Helpful when querying with EF Core .AsAsyncEnumerable().
using System.Globalization;
using CsvHelper;
//namespace AppFoo;
// Counts rows. Helps when streaming to CSV from query that uses EF Core `.AsAsyncEnumerable()`.
public class CsvWriterCounter : CsvWriter
{
int _counter;
public CsvWriterCounter(TextWriter textWriter, CultureInfo culture = null) : base(textWriter, culture ?? CultureInfo.InvariantCulture)
{
}
public int Count => _counter - 1;
public Action<int> OnNext { get; set; }
public override void NextRecord()
{
++_counter;
OnNext?.Invoke(_counter);
base.NextRecord();
}
public override Task NextRecordAsync()
{
++_counter;
OnNext?.Invoke(_counter);
return base.NextRecordAsync();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment