繁体   English   中英

F#CSV解析到C#应用程序

[英]F# CSV Parsing to C# App

我有一个C#控制台应用程序,它调用一个F#库,使用CSVTypeProvider进行一些CSV解析。 http://fsharp.github.io/FSharp.Data/reference/fsharp-data-csvprovider.html

不幸的是我对F#有些新意,所以我没有找到一种方法来有效地将解析后的数据从F#传递到C#以C#对象的形式。

假设我有一个C#数据模型:

public class Customer{
    public int ID { get; set; }
    public string Name { get; set; }
}

然后我想将数据从csv类型提供程序转换为该模型的列表:

Extractor extractor = new Extractor();
List<Customer> customers = extractor.Data;

将提取器定义为:

module internal FileLoader =
    type = Customers = CsvProvider<"C:\somefilePath", HasHeaders = true>

    let customers = Customers.Load<"C:\someFilePath">

type Extractor() =
    member this.Data = FileLoader.customers.Rows |> Seq.map(fun row -> new Customer(row.ID, row.Name))

从那里我想我可以简单地将Datamodel导入f#库并使用map函数将行值映射到c#对象,但这似乎不起作用。

编辑:

我找到了一个解决方案,但我仍然愿意接受更优雅的解决方案。

我只需要在F#Library中的C#(Customer)中创建我想要的类。

type Customer(ID : int, Name : string) =
    member this.ID = ID
    member this.Name = Name

然后我可以使用映射功能将行转换为客户对象,并将客户类型导入c#。

我会像这样在F#项目中定义我的模型类

type Customer = {id:int;name:string}

然后在你的地图中你可以

Seq.map(fun row -> {id=row.id;name=row.name})

并作为IEnumerable返回到您的C#代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM