是否可以从 F# 使用 LINQ 以及如何使用? [英] Is it possible to use LINQ from F# and how?

查看:20
本文介绍了是否可以从 F# 使用 LINQ 以及如何使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了访问一些 SharePoint 数据,我使用了 Microsoft.SharePoint.Client 库,它公开了以下 api.C# 中有示例用法(link)来自以下代码段:

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)); 

Load 方法的签名是(link)

The Signature of the Load method is (link)

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

Fsharp 编译器期望第二个参数的类型为

Fsharp Compiler expect the second paramater to be of type

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

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

我可以使用 F# 中的 Load 方法吗?

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

有一个相关的答案这里但我无法将给出的代码示例解决方案转换为上述 c# 示例.也许有人可以帮忙?涉及的类型有 list : ListCollectionlist : List

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

推荐答案

这是未经测试的,因为我没有 SharePoint 服务器,但是...

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

将允许您从 F# lambda 表达式生成 Linq 表达式,但您还需要在 lambda 参数上提供类型注释并将返回类型强制转换为obj"以匹配预期签名.如果您需要重用相同的表达式,则值得定义一些简短的辅助函数来实现.

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))

这篇关于是否可以从 F# 使用 LINQ 以及如何使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆