我有以下 F# 代码。函数 getARow
返回 (string * string * string) 选项
。在主函数中,我需要提取列值并将它们分别分配给a、b、c
。如何实现? (新手问题)
如果没有找到行,该函数可能会返回 null? getARow
返回null如何处理?
open System
open System.Data
open System.Data.Linq
open Microsoft.FSharp.Data.TypeProviders
open Microsoft.FSharp.Linq
open System.Net
open System.IO
open FSharp.Data
type dbSchema = SqlDataConnection<"Data Source=Svr;Initial Catalog=DB;Integrated Security=SSPI;">
//, LocalSchemaFile = "Schema.dbml", ForceUpdate = false >
let getARow =
let db = dbSchema.GetDataContext()
db.DataContext.Log <- System.Console.Out
let query = query {
for row in db.Table1 do
where (row.SiteID = 1)
select (Some(row.Col1, row.Col2, row.Col2)) // All Colx are strings
headOrDefault // May return null
}
query
[<EntryPoint>]
let main argv =
let aRow = getARow
printfn "%A" aRow
let a,b,c = match aRow with
| ........ // How to let a = Col1, b = Col2 and c = Col3?
| None -> failwith "Cannot find a row" // Null?
0
最佳答案
要从选项类型中提取值(无论它包含什么),您需要使用 Some <...>
模式在哪里 <...>
是一个嵌套模式,可以为值命名(如果你想要一个包含元组的单个变量)或进一步分解它(如果你想要三个单独的变量):
let a,b,c =
match aRow with
| Some(a, b, c) -> a, b, c
| None -> failwith "Cannot find a row"
或者,您可以只使用内置的 Option.get
功能:
let a,b,c = Option.get aRow
您的代码依赖于一个技巧 - 即 headOrDefault
返回 null
如果没有行 - 这将起作用,因为 null
是 None
的内部表示.但你也可以使用 an extension that adds headOrNone
使代码更漂亮。
关于f# - 获取元组选项类型变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18920342/