Reputation: 40223
I have a function in C# that is being called in F#, passing its parameters in a Microsoft.FSharp.Collections.List<object>
.
How am I able to get the items from the F# List in the C# function?
EDIT
I have found a 'functional' style way to loop through them, and can pass them to a function as below to return C# System.Collection.List:
private static List<object> GetParams(Microsoft.FSharp.Collections.List<object> inparams)
{
List<object> parameters = new List<object>();
while (inparams != null)
{
parameters.Add(inparams.Head);
inparams = inparams.Tail;
}
return inparams;
}
EDIT AGAIN
The F# List, as was pointed out below, is Enumerable, so the above function can be replaced with the line;
new List<LiteralType>(parameters);
Is there any way, however, to reference an item in the F# list by index?
Upvotes: 9
Views: 3703
Reputation: 5323
Answer to edited question:
Is there any way, however, to reference an item in the F# list by index?
I prefer f# over c# so here is the answer:
let public GetListElementAt i = mylist.[i]
returns an element (also for your C# code).
Upvotes: 1
Reputation: 5323
In my C#-project I made extension methods to convert lists between C# and F# easily:
using System;
using System.Collections.Generic;
using Microsoft.FSharp.Collections;
public static class FSharpInteropExtensions {
public static FSharpList<TItemType> ToFSharplist<TItemType>(this IEnumerable<TItemType> myList)
{
return Microsoft.FSharp.Collections.ListModule.of_seq<TItemType>(myList);
}
public static IEnumerable<TItemType> ToEnumerable<TItemType>(this FSharpList<TItemType> fList)
{
return Microsoft.FSharp.Collections.SeqModule.of_list<TItemType>(fList);
}
}
Then use just like:
var lst = new List<int> { 1, 2, 3 }.ToFSharplist();
Upvotes: 7
Reputation: 118865
In general, avoid exposing F#-specific types (like the F# 'list' type) to other languages, because the experience is not all that great (as you can see).
An F# list is an IEnumerable, so you can create e.g. a System.Collections.Generic.List from it that way pretty easily.
There is no efficient indexing, as it's a singly-linked-list and so accessing an arbitrary element is O(n). If you do want that indexing, changing to another data structure is best.
Upvotes: 12