Created
August 28, 2016 19:21
-
-
Save colinbull/60797d5377be4d841f51e4f0776a24fa to your computer and use it in GitHub Desktop.
A simple CSV file
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
type Csv private(headers : string[], data : string [] []) = | |
let headers = ResizeArray<string>(headers) | |
let data = ResizeArray(data |> Array.map (ResizeArray)) | |
static member Empty = Csv([||], [||]) | |
static member Read(file:string) = | |
let csv = CsvFile.Load(file) | |
let headers = | |
match csv.Headers with | |
| Some hs -> hs | |
| None -> failwithf "The csv file must have headers" | |
new Csv(headers, [| for header in headers do yield [|for row in csv.Rows -> row.GetColumn(header)|] |]) | |
member x.GetValue(col, indx) = | |
match data |> Seq.tryItem indx with | |
| Some row -> | |
headers | |
|> Seq.tryFindIndex ((=) col) | |
|> Option.bind (fun colIndx -> row |> Seq.tryItem colIndx) | |
| None -> None | |
member x.SetValue(col, indx, value) = | |
match data |> Seq.tryItem indx with | |
| Some row -> | |
match headers |> Seq.tryFindIndex ((=) col) with | |
| Some colIndex -> | |
row.Insert(colIndex, value) | |
| None -> | |
headers.Add(col) | |
row.Insert(headers.Count - 1, value) | |
| None -> | |
let row = ResizeArray<_>() | |
match headers |> Seq.tryFindIndex ((=) col) with | |
| Some colIndex -> | |
row.Insert(colIndex, value) | |
| None -> | |
headers.Add(col) | |
row.Insert(headers.Count - 1, value) | |
data.Insert(indx, row) | |
member x.Data | |
with get() = | |
[| | |
yield headers |> Seq.toArray | |
for row in data do | |
yield [| for value in row -> value |] | |
|] | |
override x.ToString() = | |
let sb = new Text.StringBuilder() | |
for row in x.Data do | |
sb.AppendLine(String.concat "," row) |> ignore | |
sb.ToString() | |
member x.Save(path) = | |
IO.File.WriteAllText(path, x.ToString()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment