Query expressions in F#

Not quite the same as LINQ in syntax terms, F# includes query expressions which are in essence it’s own style of LINQ.

If we assume we have a simple example of some code in C# which uses LINQ to get strings from an array where their length is 3. In C# this might look like the following

string[] sample = {"One", "Two", "Three", "Four", "Five"};

IEnumerable<string> result = 
   from s in sample 
   where s.Length == 3 
   select s;

Note: I’ve purposefully put each part of the LINQ query on a new line for easier comparison with the equivalent F# query expression.

So here’s the same in F#

let sample = [| "One" ; "Two" ; "Three" ; "Four" ; "Five" |]

let result = query {
   for s in sample do
   where (s.Length = 3)
   select s
}

The main differences are the use of the query expression syntax query { … } and the use of the for s in sample do instead of from s in sample

References

See Query Expressions (F#) for a few examples of different query expressions and how they relate to SQL queries (and more).