在 F# 中使用 C# Linq ForEach()

Using C# Linq ForEach() in F#

我正在将一些代码从 C# 转换为 F#,我需要跨过 F# 的以下行:

List<VirtualMachine> vmList = new List<VirtualMachine>();
m_vimClient.FindEntityViews(typeof(VirtualMachine), null, null, null).ForEach(vm => vmList.Add((VirtualMachine)vm));
return vmList;

我做了以下事情:

let vmList = vimClient.FindEntityViews(typedefof<VirtualMachine>, null, null, null).ForEach(vm => vmList.Add((VirtualMachine)vm))
vmList

不幸的是,Intellisense 告诉我 vmvmList 没有在 F# 代码的 ForEach() 部分定义。

我该如何解决这个问题?

您使用的 lambda 语法是 C# 语法。在 F# 中,lambda 定义为 fun vm -> ….

也就是说,您根本不需要 ForEach。 C# 版本可以在没有 lambda 的情况下编写为:

var vmList = m_vimClient.FindEntityViews(typeof(VirtualMachine), null, null, null)
    .Cast<VirtualMachine>()
    .ToList();

在 F# 中,这将是:

let vmList = m_vimClient.FindEntityViews(typedefof<VirtualMachine>, null, null, null)
                 |> Seq.cast<VirtualMachine>
                 |> Seq.toList