简体   繁体   中英

Using C# Linq ForEach() in F#

I'm translating some code from C# to F#, and I have the following lines that I need to cross over the F#:

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

I did the following:

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

Unfortunately, Intellisense is telling me that vm and vmList are not defined in the ForEach() part of the F# code.

How would I solve this problem?

The lambda syntax you used is C# syntax. In F#, a lambda is defined like fun vm -> … .

That said, you don't need the ForEach at all. The C# version could be written without the lambda as:

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

In F#, this would be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM