F # working with DataReader

let reader = selectCommand.ExecuteReader() let getBytesData (x : IDataReader) = let len = reader.GetBytes(1, int64 0, null, 0, 0); // Create a buffer to hold the bytes, and then // read the bytes from the DataTableReader. let buffer : byte array = Array.zeroCreate (int32 len) x.GetBytes(1, int64 0, buffer, 0, int32 len) |> ignore buffer let retVal = List [ while reader.Read() do yield (reader.GetString(0), getBytesData reader, reader.GetDateTime(2)) ] 

I have above code for reading bytes [] from datareader.

The getBytesData function takes the reader and returns bytes [] from the reader.

  • everything works fine, but the getBytesData function works very dysfunctionally.
  • I create a null filled byte array just to create an array, is there a way to create a dynamic expandable or fixed long array

Is there a way that I can optimize in F #?

Sorry for some question, but I started a new project in F # to squeeze all the juice out of it, so trying to get each line in the most optimal way

+4
source share
2 answers

The GetBytes IDataReader method GetBytes not actually provide any parameters for writing code in a more functional way (it takes an array that it wants to change, so we just need to give it some array ..).

So, your version of the code works fine, although it is not fully functional, you can at least keep the urgent part localized in this single function and keep the rest of your program functional (which is a good result)!

The only change I would make in your code is that I would shift the reader to understand the sequence (to make it more localized), and I would use the use keyword to make sure it is configured correctly (also, you don’t need List identifier in sequence expression):

 let retVal = [ use reader = selectCommand.ExecuteReader() while reader.Read() do yield (reader.GetString(0), getBytesData reader, reader.GetDateTime(2)) ] 
+7
source

In my experience, this is the best way to do this. Interaction with native .Net methods needs to use a few emparitiviley (thus, | | ignore), therefore encapsulating in a function, using fn as part of your functional programming. I asked questions related to using .Net methods in F #, if you are interested.

Also make sure that you also get rid of the reader.

0
source

Source: https://habr.com/ru/post/1311982/


All Articles