I have written an F# module that has a list inside:
module MyModule
type X =
{
valuex : float32
}
let l = [ for i in 1 .. 10 -> {valuex = 3.3f}]
Now from a C# class I'm trying to access the previously defined list, but I don't know how converting it:
... list = MyModule.l ; //here's my problem
I'd need something like:
IList<X> list = MyModule.l;
How can I achieve that?
As simple as:
IList<MyModule.X> list = MyModule.l.ToList();
The reason you need the conversion method rather than a cast / implicit conversion is because an FSharpList<T>
implements IEnumerable<T>
but not IList<T>
since it represents an immutable linked-list.
Note that you'll have to include FSharp.Core
as a reference in your C# project.
The FSharpList<T>
(which is the .Net name of the F# list<T>
type) doesn't implement IList<T>
, because it doesn't make sense.
IList<T>
is for accessing and modifying collections that can be accessed by index, which list<T>
is not. To use it from C#, you can either use the type explicitly:
FSharpList<MyModule.X> l = MyModule.l;
var l = MyModule.l; // the same as above
Or you can use the fact that it implements IEnumerable<T>
:
IEnumerable<MyModule.X> l = MyModule.l;
Or, if you do need IList<T>
, you can use LINQ's ToList()
, as Ani suggested:
IList<MyModule.X> l = MyModule.l.ToList();
But you have to remember that F# list is immutable and so there is no way to modify it.
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.