F# list to C# IEnumerable: most efficient method?
Asked Answered
A

1

13

I'm currently working on an F# library with GUI written in C# and I would like to ask what is the best or correct way to pass an F# (generic) list to a C# code (generic IEnumerable).

I've found three ways so far:

[1; 2; 3; 4; 5;] |> List.toSeq

[1; 2; 3; 4; 5;] |> Seq.ofList 

[1; 2; 3; 4; 5;] :> seq<int>

Is there any practical difference between these three methods, please?

Arbitration answered 31/5, 2016 at 19:54 Comment(0)
A
17

If you look in the F# library source code, you'll find out that they are all the same:

In terms of readability, I would probably use Seq.ofList or List.toSeq, especially if the code is a part of a larger F# pipeline, because then it makes the code a bit nicer:

someInput
|> List.map (fun x -> whatever) 
|> List.toSeq
Avowed answered 31/5, 2016 at 19:59 Comment(2)
To expand a bit on Tomas's excellent answer: my general recommendation on whether to use Seq.ofList or List.toSeq would be to ask yourself "What is my code using?" If (as in this example) you have a list and you want to produce a seq/IEnumerable for other code to consume, then use List.toSeq. If you have received a list and you want to get a seq for your own code to consume, use Seq.ofList. In other words, pick the function that most matches the "direction" of data flow in this particular part of your code.Naima
If you nuget FSharp.Core.Fluent you will be able to dot into the list like: [1;2;3].toSeq().Debrief

© 2022 - 2024 — McMap. All rights reserved.