简体   繁体   中英

Accessing an F# List<List<>> from inside C# code

this is an extension of my previous thread . I thought that accessing a List<List<>> would be quite similar to a simple list, but I have some problem.

Here's the F# code:

type X = 
    {
        valuex : int
    }
let l = 
    [
    for i in 1 .. 10 -> 
        [
        for j in 1 .. 10 ->
            {valuex =  i * j}
        ]

    ]

Accordingly to my previous post I tried to do the following inside C# code:

IList<IList<MyModule.X>> list = MyModule.l.ToList();

but this don't compile.
Can someone which is my error?

In this case, the type of the property is FSharpList<FSharpList<MyModule.X>> So you'll have to map each inner FSharpList to an IList<T> and then materialize the resulting sequence to a list (of lists).

This would look like:

IList<IList<MyModule.X>> list = MyModule.l
                                        .Select(inner => (IList<MyModule.X>) inner.ToList())
                                        .ToList();

Do you really need all these precise conversions? Isn't the fact that the collection is already an IEnumerable<IEnumerable<T>> good enough? In fact, FSharpList<T> itself is quite a usable type from C#, so I would stay away from these conversions unless absolutely necessary.

EDIT :

If you just need to iterate the elements, all you need is a loop:

foreach(var innerList in MyModule.l)
{
    foreach(var item in innerList)
    {
        Console.WriteLine(item.valuex);
    }     
}

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