[VB.net] 使用LINQ查詢CSV檔資料

直接用迴圈讀感覺太笨了

在網路上查到更好的做法,記錄一下

建立 user的資料結構對應 CSV檔

Public Class user
    Property name As String
    Property email As String
End Class

建立函數讀入 CSV檔傳回List (of user)

Function LoadData(ByVal srcFile As String) As List(Of user)
    Dim data As New List(Of user)

    Using tfp As New FileIO.TextFieldParser(srcFile)
        tfp.TextFieldType = FileIO.FieldType.Delimited
        tfp.SetDelimiters(vbTab)
        tfp.HasFieldsEnclosedInQuotes = True

        Dim currentRow As String()
        Dim currentLine = 0

        While Not tfp.EndOfData
            currentLine += 1
            Try
                currentRow = tfp.ReadFields()
                If currentRow.Length = 2 Then
                    data.Add(New user With {.name = currentRow(0), .email = currentRow(1)})
                End If
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End While
    End Using

    Return data
End Function

最後呼叫載入CSV檔,並使用Linq查詢

Dim data As List(Of user) = LoadData("d:\user.txt")

dim johnEmail as String = (From d In data
                            Where d.name = "john"
                            Select d).First.email