VB.Net CsvHelper 类图

问题描述 投票:0回答:3

我正在尝试使用 CsvHelper 库读取 VB.Net 中的 csv 文件,但是在将行映射到自定义类时遇到问题。我该如何用 VB 而不是 C# 来编写以下代码

public sealed class MyClassMap : CsvClassMap<MyClass>
{
    public MyClassMap()
    {
        Map( m => m.Id );
        Map( m = > m.Name );
    }
}

代码取自图书馆网站

干杯,康纳

vb.net linq csv
3个回答
3
投票

假设一个像这样的物体:

Public Class MyObject
    Public Property Id As Integer
    Public Property Name As String
End Class

你可以这样映射它:

Public NotInheritable Class MyObjectMap
    Inherits CsvClassMap(Of MyObject)

    Sub New()
        Map(Function(x) x.Id)
        Map(Function(x) x.Name)
    End Sub

End Class

0
投票

杰夫的答案略有改变:

假设一个像这样的物体:

Public Class MyObject
    Public Property Id As Integer
    Public Property Name As String
End Class

你可以这样映射它:

Public NotInheritable Class MyObjectMap
    Inherits CsvHelper.Configuration.ClassMap(Of MyObject)
    Sub New()
        Map(Function(x) x.Id)
        Map(Function(x) x.Name)
    End Sub
End Class

0
投票

在我拥有的新版本(24.0.1)中,以下代码将用于 CsvHelper 的映射

Dim textReader As TextReader = File.OpenText(filename)

Dim config = New CsvHelper.Configuration.CsvConfiguration(System.Globalization.CultureInfo.InvariantCulture)
        config.Delimiter = ","
        config.MissingFieldFound = Nothing
        config.TrimOptions = True
        config.HeaderValidated = Nothing

Dim csv = New CsvReader(textReader, config)

csv.Context.RegisterClassMap(Of ModelMyObjectMap)()

这里是地图类的示例

Public Class MyObject
    Public Property Handle As String
    Public Property Title As String
    Public Property BodyHTML As String
    Public Property Vendor As String
    Public Property Type As String
    Public Property Tags As String

End Class

Public NotInheritable Class ModelMyObjectMap
    Inherits CsvHelper.Configuration.ClassMap(Of MyObject)

    Public Sub New()
        Map(Function(m) m.Handle).Name("Handle")
        Map(Function(m) m.Title).Name("Title")
        Map(Function(m) m.BodyHTML).Name("Body (HTML)")
        Map(Function(m) m.Vendor).Name("Vendor")
        Map(Function(m) m.Type).Name("Type")
        Map(Function(m) m.Tags).Name("Tags")
   End Sub
End Class
© www.soinside.com 2019 - 2024. All rights reserved.