Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FirstOrDefault In F#

Tags:

linq-to-sql

f#

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

like image 935
Shakirov Ruslan Avatar asked May 06 '10 20:05

Shakirov Ruslan


2 Answers

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.

like image 186
kvb Avatar answered Sep 28 '22 08:09

kvb


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
like image 37
Tahir Hassan Avatar answered Sep 28 '22 07:09

Tahir Hassan