LINQ statements in F#
June 10, 2017 1 Comment
There’s very little difference between executing LINQ statements in C# and F#. Adding a reference to System.Linq in an F# file gives access to the same LINQ extension methods we’ve all come to love. There’s a choice between LINQ extension methods and LINQ queries with lambda statements. Any LINQ statement in C# can be directly ported to F# and will have the same result.
Note that many LINQ statements can be rewritten using built-in functions from the various collection types in F# such as List and Seq, e.g. List.average or Seq.map . In this short post we’ll just look at a couple of LINQ examples. There’s no point in regurgitating the various LINQ functions here. There’s a large collection on this blog available here if you are new to this topic.
F# LINQ statements return sequences which do not yet contain the result of the query. They are lazily evaluated when accessed. It’s the expected behaviour based on what we know about IQueryable and IEnumerable in C#. Here is an example where we select the odd numbers from a list of integers and select their double values. Note how the lambda statements for the Where and Select functions must of course adhere to F# syntax:
open System.Linq let someList = [0..100] let oddNumbers = someList.Where(fun n -> n % 2 = 1).Select(fun n -> n * 2).ToList() oddNumbers.ForEach(fun n -> printfn "%i" n)
oddNumbers will include 2, 6, 10, 14 etc.
We can rewrite the above in LINQ query style. Note the usage of the F# query keyword:
open System.Linq let oddNumbersWithQuery = query { for n in someList do where (n % 2 = 1) select (n * 2) } printfn "%A" oddNumbersWithQuery
Another difference is the usage of the “do” keyword that must be set after the “for” statement.
View all F# related articles here.
Pingback: F# Weekly #24, 2017 – Suave learning discount inside – Sergey Tihon's Blog