FirstOrDefault In F#

醉酒当歌 提交于 2019-12-30 17:26:21

问题


How to write FirstOrDefault Linq Query in F#? Can I use linq to sql in F# in totally?


回答1:


Note that a more idiomatic approach within F# would probably be to use something along the lines of Seq.tryFind rather than to use the LINQ operators, although it's not a drop in replacement since it returns an option value.




回答2:


Because the Seq module already has a head function of type seq<'a> -> 'a, I would define a function tryHead with signature seq<'a> -> option<'a>:

module Seq =
    let tryHead (ls:seq<'a>) : option<'a>  = ls |> Seq.tryPick Some

using it as:

[1; 2; 3] |> Seq.tryHead



回答3:


Regarding LINQ-to-SQL, see

http://blogs.msdn.com/dsyme/archive/2009/10/23/a-quick-refresh-on-query-support-in-the-f-power-pack.aspx

Regarding FirstOrDefault, it's just an extension method in the System.Linq namespace:

let l = [1;2;3]
open System.Linq 
let r = l.FirstOrDefault()



回答4:


Alternatively, you can define your own firstordefault easily:

let firstordefault list =
   match list with
   | head :: tail -> head 
   | [] -> 0 // some default value

Example:

let exampleList = [ 1; 2; 3 ]

using F# interactive,

firstordefault exampleList;;  
val it : int = 1


来源:https://stackoverflow.com/questions/2784281/firstordefault-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!