简体   繁体   中英

Retrieving items from an F# List passed to C#

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?

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 eg 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.

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();

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).

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