Last active
April 4, 2023 16:50
-
-
Save yzorg/9a450311f445ec14d71dac2d723cb7c1 to your computer and use it in GitHub Desktop.
For counting CSV rows. Helpful when querying with EF Core .AsAsyncEnumerable().
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.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