sort a structure by a string vb.net
I would like to sort a structure based on a string. In particular I am trying to sort all the items in ItemType. I know how to do it with an integer but was unsure on how to sort a string.
Module Module1
Dim itemCode(8) As String
Dim itemType(8) As String
Dim uHand(8) As Long
Dim aUnit(8) As Single
Dim sUnit(8) As Single
Dim i As Integer
Dim fs As New FileStream("file.txt", FileMode.Create, FileAccess.Write)
Dim s As New StreamWriter(fs)
Dim hdr As String
Dim bdr As String
Dim arr As String
Dim tCost As Long
Dim tSales As Long
Dim tIncome As Long
Dim tUhand As Long
Dim str As String
Structure dFile
Public ItemCode As String
Public ItemType As String
Public uhand As Long
Public aunit As Single
Public sunit As Single
End Structure
Sub Main()
arrLoad()
crFile()
rOne()
End Sub
Sub arrLoad()
IC() 'load arrays
IT()
uH()
aU()
sU()
Dim dataFile(8) As dFile
For I As Integer = 0 To 8
dataFile(I).ItemCode = itemCode(I)
dataFile(I).ItemType = itemType(I)
dataFile(I).uhand = uHand(I)
dataFile(I).aunit = aUnit(I)
dataFile(I).sunit = sUnit(I)
Next
End Sub
Sub crFile()
For i = 0 To 8
s.WriteLine(((itemCode(i) & " " & itemType(i) & " " & uHand(i) & _
" " & aUnit(i) & " " & sUnit(i))))
tCost += (uHand(i) * aUnit(i))
tSales += (uHand(i) * sUnit(i))
Next
tIncome += (tSales - tCost)
s.Close()
End Sub
[2070 byte] By [
wartech] at [2007-11-11 9:52:49]

# 1 Re: sort a structure by a string vb.net
The simplest way is to change your structure to implement IComparable. For example:
Structure dFile
Implements IComparable
Public ItemCode As String
Public ItemType As String
Public uhand As Long
Public aunit As Single
Public sunit As Single
Public Function CompareTo(ByVal obj As Object) As Integer _
Implements IComparable.CompareTo
Dim df As dFile = CType(obj, dFile)
Return Me.ItemType.CompareTo(df.ItemType)
End Function
End Structure
Having done that, you can use the built-in Array.Sort method on your array of dFile structures.
# 2 Re: sort a structure by a string vb.net
Thanks for the help! I was able to sort by item type, but did not keep the structure together when doing so. I had records that were being mismatched. Where did I go wrong?
Structure dFile
Implements IComparable
Public ItemCode As String
Public ItemType As String
Public uhand As Long
Public aunit As Single
Public sunit As Single
Public Function CompareTo(ByVal obj As Object) As Integer _
Implements IComparable.CompareTo
Dim datafile As dFile = CType(obj, dFile)
Return Me.ItemType.CompareTo(datafile.ItemType)
End Function
End Structure
Sub arrLoad()
IC() 'load arrays
IT()
uH()
aU()
sU()
Dim datafile(8) As dFile
For I As Integer = 0 To 8
dataFile(I).ItemCode = itemCode(I)
dataFile(I).ItemType = itemType(I)
dataFile(I).uhand = uHand(I)
dataFile(I).aunit = aUnit(I)
dataFile(I).sunit = sUnit(I)
Next
Array.Sort(datafile, itemType)
End Sub