Created
April 2, 2023 15:03
-
-
Save michaeloyer/e6a3f94755d0405a56791acda03dc51d to your computer and use it in GitHub Desktop.
CSV Reading in F# with CsvHelper
This file contains hidden or 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
#r "nuget: CsvHelper" | |
open System | |
open CsvHelper | |
type Transaction = { Amount: float; Date: DateOnly; Description: string } | |
let readTransactions() : Transaction list = [ | |
use reader = new IO.StringReader(""" | |
Account Number,Posted Date,Check,Description,Debit,Credit | |
******,2023-03-01,,"Pay Check",,100 | |
******,2023-03-01,101,"Restaurant",10,, | |
""" ) | |
use csvReader = new CsvReader(reader, Globalization.CultureInfo.CurrentCulture) | |
let transactions = | |
csvReader.GetRecords< // Inlined Anonymous Record | |
{| Debit: Nullable<float> | |
Credit: Nullable<float> | |
``Posted Date``: DateOnly // Property Name with spaces | |
Description: string |}>() | |
for row in transactions do | |
yield { | |
Amount = if row.Debit.HasValue | |
then row.Debit.Value | |
else -row.Credit.Value | |
Date = row.``Posted Date`` | |
Description = row.Description | |
} | |
] | |
readTransactions() |> printfn "%A" | |
// [{ Amount = -100.0; Date = 3/1/2023; Description = "Pay Check"; Source = "Bank Account" }; | |
// { Amount = 10.0; Date = 3/1/2023; Description = "Employer"; Source = "Bank Account" }] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment