Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translating Linq to a FSharp expression

Tags:

linq

f#

The DocumentDB has a walk-though and sample project in C# that I am working through in FSharp. One of the 1st tasks is to locate an existing datbase. The C# code is this

var database = client.CreateDatabaseQuery().Where(db => db.Id == "FamilyRegistry").ToArray().FirstOrDefault();

I am attempting to do the same line in FSharp but I am not getting the .Where even though I am referencing the same libraries. Instead I am getting this:

enter image description here

Am I thinking about the problem wrong? Thanks in advance.

like image 403
Jamie Dixon Avatar asked Dec 05 '22 04:12

Jamie Dixon


1 Answers

Linq isn't specific to C#. Even in C# you need to add a reference to System.Linq.dll and a using System.Linq; statement. The C# project templates already include these statements.

In F# you need to do the same, ensure your project has a reference to System.Linq and add an open System.Linq statement

There are at least two more idiomatic ways:

  1. You can use the Seq module's functions with the pipeline operator achieve the same result as method chaining, eg:

    let random = new System.Random()
    Seq.initInfinite (fun _ -> random.Next())
    |> Seq.filter (fun x -> x % 2 = 0)
    |> Seq.take 5
    |> Seq.iter (fun elem -> printf "%d " elem)
    printfn ""
    

    seq<'T> is a synonym of IEnumerable<T> so if you apply the methods to an IQueryable it will force the query's execution.

  2. You can use Query Expressions, equivalent to LINQ's SQL-like syntax:

    let countOfStudents =
        query {
            for student in db.Student do
            select student
            count
        }
    

    query returns a proper IQueryable<T>

Your specific query could be something like this:

let database =  
    query {
        for db in client.CreateDatabaseQuery()
        where db.Id == "FamilyRegistry"
        select db
        headOrDefault
    }
like image 83
Panagiotis Kanavos Avatar answered Dec 29 '22 01:12

Panagiotis Kanavos