Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello to all,
I don't have idea how to sort listbox items by some number in the middle of the text.
For example, my listbox has populated list with items in the format like:
VB
ListBox1.Items.Add("Plate: " & oPlateName & "; Angle: - " & strAngle & "; Diameter: " & strDiameter)


And list has to be sorted by the value:
strAngle

which is somewhere in the middle of the listbox item.

Any help is very appreciated.
TK

What I have tried:

What I have tried is:

VB
Dim orderedList As List(Of String) = (From item In myList Order By Integer.Parse(item.Substring(item.IndexOf("; Angle: - ") + 1)) Descending Select item).ToList
Posted
Updated 3-Jul-17 1:42am
v3
Comments
Richard MacCutchan 2-Jul-17 8:26am    
And what happened when you tried that code?
Michael_Davies 2-Jul-17 9:18am    
What result are you getting in orderedList, does it meet your expectations and if so what is wrong.

Rarely use a listbox, prefer listview set to detailed and add a handler for sorting so it sorts as you add items to the list or turn sorting off, build the list then sort.
Michael_Davies 2-Jul-17 9:30am    
Why not use a ListView in detail mode add a column for each item Plate, Angle & Diameter then set the sort on the Angle column.

Is this WinForms? If so, you can do this:

VB
Public Class PlateItem
    Public Plate As String
    Public Angle As Decimal
    Public Diameter As Decimal
    Public Overrides Function ToString() As String
        Return "Plate: " & Plate & "; Angle: - " & Angle & "; Diameter: " & Diameter
    End Function
End Class

'In your function
Dim plateItems As New List(Of PlateItem)
'Loop through items to add
plateItems.Add(New PlateItem with {.Plate = oPlateName, .Angle = strAngle, .Diameter = strDiameter})
'Finish Adding
lstPlateList.Items.AddRange(plateItems.OrderBy(Function(p) p.Angle).ToArray) 'This line had an error. Fixed.


That will also let you pull out a PlateItem object from lstPlate.SelectedItem which you can pull the angle and diamter from, without needing the string manipulation
 
Share this answer
 
v2
I have done it by splitting a string. Here is a solution.
'Sorting by Angle
  Dim items = (From item In lstPlateList.Items
               Let parts = item.ToString.Split(New String() {"; Angle: - ", "; Diameter: "}, StringSplitOptions.None)
               Order By CInt(parts(1))
               Select item).ToArray
  lstPlateList.Items.Clear()
  lstPlateList.Items.AddRange(items)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900