f# CSV解析到c#应用程序

本文关键字:应用程序 CSV | 更新日期: 2023-09-27 17:50:54

我有一个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))

从那里,我认为我可以简单地导入数据模型到f#库,并使用map函数映射行值到c#对象,但这似乎不太工作。

编辑:

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

我只需要在f#库中创建我想要的c# (Customer)类。

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

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

f# CSV解析到c#应用程序

我将在f#项目中像这样定义我的模型类

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

那么在你的地图中你可以

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