Search code examples
joinf#clausec#-to-f#

How to write join with composite key clause in FSharp query expressions?


How to write this C# join with composite key clause in F#? :

join k in DataContext.Catalogs on
   new { id = o.IDENT, v = o.VZ } equals
   new { id = k.IDENT, v = k.VZ }

This is similiar question to this: groupby multiple columns in a F# 3.0 query which is still not answered. But I can't believe it is not easy possible to write it in FSharp.

Thanks


Solution

  • Use tuples containing the key fields you want:

    query {
      for o in DataContext.OTable do
      join k in DataContext.Catalogs on
       ((o.IDENT, o.VZ) = (k.IDENT, k.VZ))
      select (o.IDENT, k.VZ)
    }
    

    Note that you can't create an anonymous type with named fields in F#, like you can in C#. Tuples are probably the closest and most idiomatic translation. See Tomas's answer here.