Retrieving items from an F# List passed to C#

丶灬走出姿态 提交于 2019-12-05 19:09:29

问题


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?


回答1:


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.




回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/661095/retrieving-items-from-an-f-list-passed-to-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!