【问题标题】:Best method For Sorting a tab delimited CSV into an object?将制表符分隔的 CSV 排序为对象的最佳方法?
【发布时间】:2016-11-20 10:54:22
【问题描述】:

我有一个看起来像这样的对象:

Public Class KeyWordObject
Private LocalSearches As String
Private AdvertiserCompetition As String
Private NumberOfWords As String

Public Sub New()
    ' Leave fields empty. 
End Sub

Public Sub New(ByVal LS As String, ByVal AC As String, ByVal NW As String)
    LocalSearches = LS
    AdvertiserCompetition = AC
    NumberOfWords = NW
End Sub

Public Property LocalSearchAmount As String
    Get
        Return LocalSearches
    End Get
    Set(ByVal value As String)
        LocalSearches = value
    End Set
End Property

Public Property AdvertiserCompetitionAmount As String
    Get
        Return AdvertiserCompetition
    End Get
    Set(ByVal value As String)
        AdvertiserCompetition = value
    End Set
End Property

Public Property WordCount As String
    Get
        Return NumberOfWords
    End Get
    Set(ByVal value As String)
        NumberOfWords = value
    End Set
End Property

结束类

我正在尝试解析具有以下标头的 CSV 文件,如下所示:

Ad group    Keyword     Avg. Monthly Searches (exact match only)    Competition    Suggested bid    Impr. share Organic impr. share

我想从关键字 Avg 中获取数据。每月搜索和竞争列,并将它们放入一个对象中。解析这些数据的最佳方法是什么?

【问题讨论】:

  • CSVHelper 很容易做到这一点。告诉它忽略第一行,然后设置一个 Map 来告诉它哪个 csv cols 映射到哪些属性,而其中一些被忽略。返回一个IEnumerable<T>,如果你想要一个KeyWordObject项目的列表,添加.ToList()就完成了。
  • 不清楚您的目标是对具有相同关键字的行进行计数/求和,还是要为文件中的每一行创建类的对象。你能解释得更好吗?
  • 您好抱歉不清楚。我想为文件中的每一行创建一个对象,只从某些列中获取数据。
  • 我会调查 CSVHelper 感谢您的建议。
  • 使用 OleDb 的代码更少 stackoverflow.com/questions/6813607/…

标签: vb.net csv


【解决方案1】:

我最终选择了 CSVHelper,这是对我有用的解决方案。感谢其他建议。

     Dim TEMPKEYWORDPATH = Directory.GetCurrentDirectory + "/" + "KeywordsTemp" + ".csv"
Public Function CSVtoObject(CsvPath As String)
    Dim csv = New CsvReader(File.OpenText(TEMPKEYWORDPATH))
    csv.Configuration.RegisterClassMap(Of MyCustomObjectMap)()
    csv.Configuration.WillThrowOnMissingField = False
    csv.Configuration.Delimiter = vbTab

    Dim ListOfKeywords = csv.GetRecords(Of KeyWordObject).ToList()
    Return ListOfKeywords
End Function

Public NotInheritable Class MyCustomObjectMap
    Inherits CsvClassMap(Of KeyWordObject)
    Public Sub New()
        Map(Function(m) m.Keyword).Index(1)
        Map(Function(m) m.LocalSearchAmount).Index(3)
        Map(Function(m) m.AdvertiserCompetitionAmount).Index(4)
        Map(Function(m) m.WordCount).Ignore()
    End Sub
End Class

【讨论】:

    猜你喜欢
    • 2014-12-30
    • 2011-02-01
    • 2013-10-15
    • 2011-02-01
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 2021-02-23
    • 2011-01-24
    相关资源
    最近更新 更多