Choub890
Choub890

Reputation: 1163

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?

Upvotes: 0

Views: 506

Answers (1)

Jay
Jay

Reputation: 57919

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

Upvotes: 4

Related Questions