我有以下F#代码.该函数getARow返回(string * string * string) option.在main函数中,我需要提取列值并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
Run Code Online (Sandbox Code Playgroud)
要从选项类型中提取值(无论它包含什么),您需要使用Some <...>模式,其中<...>嵌套模式可以为值赋值(如果您想要包含元组的单个变量)或进一步分解它(如果你想要三个独立的变量):
let a,b,c =
match aRow with
| Some(a, b, c) -> a, b, c
| None -> failwith "Cannot find a row"
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用内置Option.get函数:
let a,b,c = Option.get aRow
Run Code Online (Sandbox Code Playgroud)
你的代码依赖于一个技巧 - 如果没有行则headOrDefault返回null- 这将起作用,因为null它是内部表示None.但是你也可以使用一个扩展来增加headOrNone代码使代码更好.
| 归档时间: |
|
| 查看次数: |
1350 次 |
| 最近记录: |