4

In order to access some SharePoint data I use the Microsoft.SharePoint.Client Library which exposes the following api. There are example usage in C# (link) from which is the following snippet:

ClientContext context = new ClientContext("http://SiteUrl"); 
Web web = context.Web; 
context.Load(web.Lists, 
             lists => lists.Include(list => list.Title, // For each list, retrieve Title and Id. 
                                    list => list.Id)); 

The Signature of the Load method is (link)

public void Load<T>(
    T clientObject,
    params Expression<Func<T, Object>>[] retrievals
)
where T : ClientObject

Fsharp Compiler expect the second paramater to be of type

Linq.Expressions.Expression<Func<'a,obj>>

or

Linq.Expressions.Expression<Func<'a,obj>> []    

Can I use the Load Method from F# and how ?

There is a related answer here but I cant translate the give code example solution to the above c# example. Maybe one can help? The types involved are list : ListCollection and list : List

Community
  • 1
  • 1
fbehrens
  • 6,115
  • 2
  • 19
  • 22
  • The given answer to this question is extremely useful to Sharepoint developers in particular. It contains critical details that are not present in the more general question about F# lambdas to LINQ. Voting to reopen. – Brian Berns Mar 25 '21 at 01:02

1 Answers1

6

This is untested because I don't have a SharePoint server, but...

open System.Linq.Expressions
type Expr = 
    static member Quote(e:Expression<System.Func<_, _>>) = e

Will allow you to make Linq expressions from the F# lambdas, but you'll also need to give type annotations on the lambda parameters and cast the return types to 'obj' to match the expected signature. If you need to reuse the same expressions, it would be worth defining some short helper functions to do it.

let getTitle = Expr.Quote(fun (list : List) -> list.Title :> obj)
let getId    = Expr.Quote(fun (list : List) -> list.Id :> obj)

And use them to avoid the function calls becoming unreadable

context.Load(web.Lists, 
    Expr.Quote(fun (lists : ListCollection) -> lists.Include(getTitle, getId) :> obj))
fbehrens
  • 6,115
  • 2
  • 19
  • 22
marklam
  • 5,346
  • 1
  • 24
  • 26