I have a function that will parse the results of a DataReader, and I don't know how many items are returned, so I want to use a while..do loop to iterate over the reader, and the outcome should be a list of a certain type.
(fun(reader) ->
[
while reader.Read() do
new CityType(Id=(reader.GetInt32 0), Name=(reader.GetString 1), StateName=(reader.GetString 2))
])
This is what I tried, but the warning I get is:
This expression should have type 'unit', but has type 'CityType'. Use 'ignore' to discard the result of the expression, or 'let'
to bind the result to a name.
So what is the best way to iterate over a DataReader and create a list?
you can use list comprehension:
[
while reader.Read() do
let d = new CityType(Id=(reader.GetInt32 0), Name=(reader.GetString 1), StateName=(reader.GetString 2))
yield d
]
Here is one more example:
/// The squares of the first 10 integers
let squaresOfOneToTen = [ for x in 0..10 -> x*x ]
or
let squaresOfOneToTen = [ for x in 0..10 do yield x*x ]
You can also do it for sequences and arrays:
seq {
for i=1 to 9 do
for j=1 to 9 do
yield (i,j,i*j)
}
[| for i=1 to 100 do yield i*i |]
you can also yield a sub sequence in a sequence(yield!), here is an example using Project Euler 31.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With