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

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

问题描述

为了访问某些SharePoint数据,我使用Microsoft.SharePoint.Client库,该库公开以下api.C#(链接)中有示例用法以下代码段:

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方法的签名为(链接)

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:ListCollection list: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天全站免登陆