Schau Dir mal diese Funktion an ...
''' <summary>Klasse zur Aufbewahrung eines SortierSchlüssels und
' zugehörigem Index
''' </summary>
Public Class SortItem
Implements IComparable(Of SortItem)
Public Property FileSortString As String
Public Property FileRowIndex As Integer
Public Function CompareTo(other As SortItem) As Integer _
Implements System.IComparable(Of SortItem).CompareTo
Return Me.FileSortString.CompareTo(other.FileSortString)
End Function
End Class
''' <summary>Aufbau eines Sortier-Zeigers zu Zeilen einer CSV-Datei</summary>
''' <param name="CSVFile">Pfad einer CSV-Datei</param>
''' <param name="TextEncoder">Text-Encoding (meist: UTF8)</param>
''' <param name="columnindex">Array mit nullbasierten Indices der
''' hierarchischen Sortierspalten (0=höchste Hierarchie-Stufe)</param>
''' <param name="columnlength">Array mit Angaben zur Länge der
' Sortier-Teilschlüssel</param>
''' <param name="sortlst">sortierte Liste mit den Sortierschlüsseln und
' den FileRowIndices</param>
Public Function FillSortList(ByVal CSVFile As String, _
ByVal TextEncoder As System.Text.Encoding, _
ByVal columnindex() As Integer, _
ByVal columnlength() As Integer, _
ByRef sortlst As List(Of SortItem)) As Integer
sortlst = New List(Of SortItem)
If Not IO.File.Exists(CSVFile) Then Return -1
If Not IO.Path.GetExtension(CSVFile).ToLower = ".csv" Then Return -1
If columnindex Is Nothing OrElse columnindex.Length = 0 Then Return -1
If columnlength Is Nothing OrElse _
Not columnlength.Length = columnindex.Length Then Return -1
Dim mincolumnindex As Integer = _
Aggregate ind As Integer In columnindex Distinct Into Min()
If mincolumnindex < 0 Then Return -1
Dim maxcolumnindex As Integer = _
Aggregate ind As Integer In columnindex Distinct Into Max()
If (Aggregate ind As Integer In columnlength _
Distinct Into Min()) < 3 Then Return -1
Try
Dim fri As Integer = -1, fss As String = "", content As String = ""
Using sr As New IO.StreamReader(CSVFile, TextEncoder)
While Not sr.EndOfStream
Dim fields() As String = sr.ReadLine.Split(";"c)
If fields.Length > maxcolumnindex Then
fri += 1 : fss = ""
For i As Integer = 0 To columnindex.Length - 1
content = fields(columnindex(i)).ToString.ToLower
'Länge des Inhalts an Vorgabe anpassen
Dim adds As Integer = columnlength(i) - _
content.Length
If adds > 0 Then
content &= New String(" "c, adds)
ElseIf adds < 0 Then
content = content.Substring(0, columnlength(i))
End If
fss &= content & " "
Next i
sortlst.Add(New SortItem With _
{.FileRowIndex = fri, .FileSortString = _
fss})
End If
End While
End Using
If sortlst.Count = 0 Then Return 0
sortlst.Sort()
Return sortlst.Count
Catch ex As Exception
Return -1
End Try
End Function Anwendungsbeispiel:
Dim lst As New List(Of SortItem)
'Liste mit Sortierschlüsseln füllen und sortieren
Dim index As Integer = FillSortList("C:\daten\sortable.csv", _
System.Text.Encoding.UTF8, {0, 1}, {5, 3}, lst)
'Suche nach einem Schlüssel
index = lst.BinarySearch(New SortItem With {.FileSortString = "xxxx yyy "}) |