query Examples
This page was last reviewed on Nov 23, 2023.
Dot Net Perls
Query. 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.
Example. 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.
Part 1 With this query, we count all the elements in the array of numbers. Since there are 4 elements, the result is 4.
Part 2 It is possible to use sorting in query expressions. We use the sortBy clause to order the numbers from low to high.
Part 3 With "where" we filter elements with a query. Here we keep numbers only greater than or equal to 50, which leaves 55.
Part 4 With 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
Query results. 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.
And The results are discovered lazily. So the queries are only executed when the 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 23, 2023 (new).
© 2007-2024 Sam Allen.