我不太了解排序的主题但是这里说的是:我正在尝试对音乐库进行排序(逗号分隔在csv文件中。一些例子):
1,Sweet Home Alabame,Lynyrd Skynyrd,4:40,Classic Rock
2,Misirlou,Dick Dale,2:16,Surf Rock
我需要按字母顺序(按曲目标题)对它们进行排序,但我不知道两件事:1。为什么我目前的技术不起作用:
Dim array() As String = {}
sr = New StreamReader("library.csv")
counter = 1
Do Until sr.EndOfStream
array(counter) = sr.ReadLine()
counter += 1
Loop
System.Array.Sort(Of String)(array)
Dim value As String
For Each value In array
Console.WriteLine(value)
Next
Console.ReadLine()
我不知道这是否是最好的排序方式。然后我也需要显示它们。我可以在没有排序的情况下做到这一点,但无法弄清楚如何通过排序来做到这一点。
请帮助(来自那些与我不同的人,知道他们在做什么)。
答案 0 :(得分:1)
现在你将所有字段放在一个长文本字符串中(每行)。
为了按特定字段排序,您需要构建行和列矩阵。例如,DataTable
。
这是一个应该为你做的技巧:
https://www.codeproject.com/Articles/11698/A-Portable-and-Efficient-Generic-Parser-for-Flat-F
以下是文章中的示例用法代码,转换为VB:
Public Class CsvImporter
Public Sub Import()
Dim dsResult As DataSet
' Using an XML Config file.
Using parser As New GenericParserAdapter("MyData.txt")
parser.Load("MyData.xml")
dsResult = parser.GetDataSet()
End Using
' Or... programmatically setting up the parser for TSV.
Dim strID As String, strName As String, strStatus As String
Using parser As New GenericParser()
parser.SetDataSource("MyData.txt")
parser.ColumnDelimiter = vbTab.ToCharArray()
parser.FirstRowHasHeader = True
parser.SkipStartingDataRows = 10
parser.MaxBufferSize = 4096
parser.MaxRows = 500
parser.TextQualifier = """"c
While parser.Read()
strID = parser("ID")
strName = parser("Name")
' Your code here ...
strStatus = parser("Status")
End While
End Using
' Or... programmatically setting up the parser for Fixed-width.
Using parser As New GenericParser()
parser.SetDataSource("MyData.txt")
parser.ColumnWidths = New Integer(3) {10, 10, 10, 10}
parser.SkipStartingDataRows = 10
parser.MaxRows = 500
While parser.Read()
strID = parser("ID")
strName = parser("Name")
' Your code here ...
strStatus = parser("Status")
End While
End Using
End Sub
End Class
还有来自here的内容,证明DataTable
用法:
Dim csv = "Name, Age" & vbCr & vbLf & "Ronnie, 30" & vbCr & vbLf & "Mark, 40" & vbCr & vbLf & "Ace, 50"
Dim reader As TextReader = New StringReader(csv)
Dim table = New DataTable()
Using it = reader.ReadCsvWithHeader().GetEnumerator()
If Not it.MoveNext() Then
Return
End If
For Each k As var In it.Current.Keys
table.Columns.Add(k)
Next
Do
Dim row = table.NewRow()
For Each k As var In it.Current.Keys
row(k) = it.Current(k)
Next
table.Rows.Add(row)
Loop While it.MoveNext()
End Using
this Q&A说明了如何按给定列对DataTable
进行排序。