我有一个 C# 控制台应用程序调用 F# 库,该库使用 CSVTypeProvider 进行一些 CSV 解析。 (http://fsharp.github.io/FSharp.Data/reference/fsharp-data-csvprovider.html)
不幸的是,我对 F# 有点陌生,所以我还没有找到一种方法来以 C# 对象列表的形式有效地将解析后的数据从 F# 传递到 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;
Extractor 定义为:
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#(客户)中创建我想要的类。
type Customer(ID : int, Name : string) =
member this.ID = ID
member this.Name = Name
然后我可以使用映射函数将行转换为客户对象并将客户类型导入到 C#。
最佳答案
我会像这样在 F# 项目中定义我的模型类
type Customer = {id:int;name:string}
然后在你的 map 中你可以
Seq.map(fun row -> {id=row.id;name=row.name})
并作为 IEnumerable 返回到您的 C# 代码。
关于c# - F# CSV 解析到 C# 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30477630/