-
Notifications
You must be signed in to change notification settings - Fork 146
/
Copy pathDataTable.fs
99 lines (82 loc) · 2.89 KB
/
DataTable.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
namespace FSharp.Data.Sql
open System.Collections.Generic
open System.Data
module DataTable =
let map f (dt:DataTable) =
[
for row in dt.Rows do
yield row |> f
]
let iter f (dt:DataTable) =
for row in dt.Rows do
f row.ItemArray
let toList(dt:DataTable) = map id dt
let groupBy f (dt:DataTable) =
map f dt
|> Seq.groupBy (fst)
|> Seq.map (fun (k, v) -> k, Seq.map snd v)
let cache (cache:IDictionary<string,'a>) f (dt:DataTable) =
for row in dt.Rows do
match f row with
| Some(key,item) -> cache.Add(key,item)
| None -> ()
cache.Values |> Seq.toList
let mapChoose (f:DataRow -> 'a option) (dt:DataTable) =
if isNull dt then []
else
[
for row in dt.Rows do
match f row with
| Some(a) -> yield a
| None -> ()
]
let choose (f : DataRow -> DataRow option) (dt:DataTable) =
let copy = dt.Clone()
copy.Rows.Clear()
for row in dt.Rows do
match row |> f with
| Some(a) -> copy.Rows.Add(a.ItemArray) |> ignore
| None -> ()
copy
let filter f (dt:DataTable) =
choose (fun r ->
if f r
then Some r
else None
) dt
let headers (dt:System.Data.DataTable) =
[
for col in dt.Columns do
yield col.ColumnName
]
let printDataTable (dt:System.Data.DataTable) =
if isNull dt then ()
else
let widths = Dictionary<int, int>()
let computeMaxWidth indx length =
let len =
match widths.TryGetValue(indx) with
| true, len -> max len length
| false, _ -> length
widths.[indx] <- len
let i = ref 0
for col in dt.Columns do
computeMaxWidth !i col.ColumnName.Length
incr i
let rows =
dt
|> map (fun r -> r.ItemArray)
|> List.fold (fun rows row ->
let values = row |> Array.map (fun x -> x.ToString().Trim()) |> List.ofArray
values |> List.iteri (fun i x -> computeMaxWidth i x.Length)
values :: rows
) []
i := 0
for col in dt.Columns do
printf "%*s " (widths.[!i] + 2) col.ColumnName
incr i
printfn ""
for row in rows |> List.rev do
for (index,value) in row |> List.mapi (fun i x -> i,x) do
printf "%*s " (widths.[index] + 2) value
printfn ""