此表达式正确评估为225.58:
let alfki = ctx.``[dbo].[Customers]``.Individuals.ALFKI
let changeNoneToZero x = match x with | Some v -> v | None -> 0m
let freights = alfki.FK_Orders_Customers |> Seq.map (fun x -> changeNoneToZero x.Freight) |> Seq.sum
对应于以下数据库查询:
select SUM(freight)
from dbo.Orders
where CustomerID = (
select CustomerID from Customers
where CustomerID = 'ALFKI')
是否存在changeNoneToZero
函数的内置等效或近似模拟?我可以寻求Seq.sumBy
代替吗?
答案 0 :(得分:4)
@ ildjarn使用Seq.choose
的方法。不是将None
转换为0m然后对所有内容求和,而是仅选择那些不是None
并将它们输入Seq.sum
的值:
let freights = alfki.FK_Orders_Customers
|> Seq.choose (fun x -> x.Freight)
|> Seq.sum
谢谢@ildjarn!
答案 1 :(得分:2)
您还可以使用Option.fold
:
alfki.FK_Orders_Customers |> Option.fold (fun _ a -> a) 0m
你可以把它变成通用的:
let inline valOrZero ov = ov |> Option.fold (fun _ a -> a) LanguagePrimitives.GenericZero