With LINQ we can use advanced query expressions in F# code. These queries, which are specified with the query keyword, are similar to SQL statements on native code.
In F#, we begin query expressions with the query keyword, and then the "for" keyword. We can use select to get values as a result, or other functions like count or lastOrDefault
.
We test 4 different query expressions in this example. Some of the queries return a single result value, and others return a sequence we evaluate with Seq.iter
.
sortBy
clause to order the numbers from low to high.lastOrDefault
, we either keep the last result if one exists, or the default value—which for int
is 0.let numbers = [45; 5; 55; 10] // Part 1: use query expression with count. let query1 = query { for number in numbers do select number count } printfn $"QUERY1: {query1}" // Part 2: use query with sortBy and display with Seq.iter. let query2 = query { for number in numbers do sortBy number select number } query2 |> Seq.iter (fun n -> printfn $"QUERY2: {n}") // Part 3: use query with where. let query3 = query { for number in numbers do where (number >= 50) select number } for n in query3 do printfn $"QUERY3: {n}" // Part 4: use query with where and lastOrDefault. let query4 = query { for number in numbers do where (number = 3000) lastOrDefault } printfn $"QUERY4: {query4}"QUERY1: 4 QUERY2: 5 QUERY2: 10 QUERY2: 45 QUERY2: 55 QUERY3: 55 QUERY4: 0
A query returns an IEnumerable
collection. We can evaluate the contents of the IEnumerable
in F# with Seq.iter
or with a for-do
loop.
Seq.iter
or for-do
are run.While the query keyword block complicates syntax, queries in F# are still powerful and concise. They are probably the easiest way to perform complex sorts and filtering operations.