how do you convert an obj list to int type. I am trying to add two lists using a map function below but it doesn't work on obj lists.
let query f=
seq{
let cmd = new OleDbCommand( "SELECT * FROM F" );
let conn = new OleDbConnection( @"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=D:\Users\df\Documents\Vfolio.accdb;
Persist Security Info=False;" )
conn.Open()
let DAdapt = new OleDbDataAdapter("SELECT * FROM F",conn)
let DTab = new DataSet()
let i= DAdapt.Fill(DTab)
let rowCol = DTab.Tables.[0].Rows
let rowCount = rowCol.Count
for i in 0 .. (rowCount - 1) do
yield f (rowCol.[i])
}
let u= query(fun row -> row.[0])
let a= List.ofSeq u
let v=query(fun row -> row.[1])
let b= List.ofSeq v
let c = List.map2 (fun x y-> x + y) a b
error msg: The type 'obj' does not support the operator '+'
Because
row.[i]
returns typeobj
, youru
andv
becomeseq<obj>
, and thus youra
andb
become typeList<obj>
, and thereforex
andy
are inferred to have typeobj
, and of course, you can't add twoobj
s, which is exactly what the compiler tells you.If you are sure that
row.[0]
androw.[1]
are numbers of some kind, you should apply the appropriate cast, for example:You can apply this cast in other places, too, depending on your taste and requirements, for example:
Or:
But I like the first example best, because it applies the cast at the earliest known point and results in the least amount of extra code.
But beware: if
row.[0]
turns out to be not anint
at runtime, you will get anInvalidCastException
.P.S. In your
List.map2
call, you could specify(+)
directly instead of wrapping it in an extra lambda:P.P.S Also, it seems that your
List.ofSeq
calls are wasteful, forSeq
also has amap2
:P.P.P.S Also, have you noticed that each of the two calls to
query
generates its own DB connection, command, adapter, and dataset? Did you intend this or did you mean to only have one connection and then fetch different columns from the result? If so, you should only callquery
once: