Skip to content

Instantly share code, notes, and snippets.

@smoothdeveloper
Created July 5, 2016 14:46
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 smoothdeveloper/702b19a1b633b6840b0b724e6c361bf9 to your computer and use it in GitHub Desktop.
Save smoothdeveloper/702b19a1b633b6840b0b724e6c361bf9 to your computer and use it in GitHub Desktop.
DataTableMaker
open System
open System.Data
module DataTableMaker =
type ColumnMaker<'t> = { Name: string; Type: Type; GetValue: 't -> obj }
let makeColumn name (f: _ -> 'c) =
{ Name = name; Type = typeof<'c>; GetValue = f >> box }
let makeDataTable items (columns : #_ seq)=
let table = new DataTable()
let addColumn colName colType = table.Columns.Add(colName, colType) |> ignore
let addRow (data: obj seq) = Seq.toArray data |> table.Rows.Add |> ignore
for c in columns do
addColumn c.Name c.Type
for i in items do
columns
|> Seq.map (fun c-> c.GetValue i)
|> addRow
table
open DataTableMaker
open System.Runtime.CompilerServices
// make this stuff easy to call from C#/VB.NET with helper and extension methods
type ColumnMaker =
static member Make(columnName, getValue: Func<'t, 'c>) =
{ Name = columnName; Type = typeof<'c>; GetValue = getValue.Invoke >> box }
[<Extension>]
module EnumerableExtensions =
/// create a <see cref="DataTable"/> from a sequence
/// of items (<see paramref="items"/>) and column descriptors (<see paramref="columns"/>)
/// <param name="items">the values from wich corresponding rows (<see cref="DataRow">) will be created</param>
/// <param name="columns"></param>
[<Extension>]
let MakeDataTable(items, [<ParamArray>] columns) = DataTableMaker.makeDataTable items columns
(* how to call:
let foo = [(1,2);(3,4)]
let t = DataTableMaker.makeDataTable foo [|makeColumn "a" fst|]
*)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment