find the shortest name in a listbox

dl21

New member
Joined
Oct 29, 2008
Messages
1
Programming Experience
Beginner
there are 20 names in a listbox, user can choose any for them at least one. after choose some of them, how to find the shortest name and sort it at the top of the 20.thanks a lot!
 
This is an interesting one, what I ended up doing was looping through the SelectedIndicies collection, adding each of those index items to a new list (of string, since these are names) and removing them from the listbox at the same time, then sorting them in the smallest to largest order took some thought, but what i did was looped through the new list looking for the largest item and adding it at position 0 of the list box and of course removing it from the list at the same time. Here's the code I used:
VB.NET:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim LS As New List(Of String)
        Dim Counter As Integer = 0I
        Dim CurrLength, CurrIndex, TopIndex As Integer

        For Counter1 As Integer = ListBox1.SelectedIndices.Count - 1I To 0I Step -1I
            LS.Add(ListBox1.Items(ListBox1.SelectedIndices(Counter1)))
            ListBox1.Items.RemoveAt(ListBox1.SelectedIndices(Counter1))
        Next Counter1

        TopIndex = LS.Count
        Do While Counter < TopIndex
            CurrLength = 0I
            CurrIndex = 0I
            For Counter1 As Integer = 0I To LS.Count - 1I
                If LS(Counter1).Length > CurrLength Then
                    CurrLength = LS(Counter1).Length
                    CurrIndex = Counter1
                End If
            Next Counter1
            ListBox1.Items.Insert(0I, LS(CurrIndex))
            LS.RemoveAt(CurrIndex)
            Counter += 1I
        Loop
    End Sub
Good thing you're using VS 2005 too
 
Sorting by string length can easily be done with the Sort method of the List(Of T), here you can use the overload that takes a Comparison(Of T) delegate to define your own sorting mechanism. Such a method can be defined like this:
VB.NET:
Function StringLengthComparison(ByVal a As String, ByVal b As String) As Integer
    Return a.Length.CompareTo(b.Length)
End Function
A quick usage sample:
VB.NET:
Dim l As New List(Of String)
l.Add("long string")
l.Add("longer string")
l.Add("short")
l.Sort(AddressOf StringLengthComparison)
MsgBox(String.Join(vbNewLine, l.ToArray))
The explicit long form for l.Sort(..) is this:
VB.NET:
l.Sort(New Comparison(Of String)(AddressOf StringLengthComparison))
 
Back
Top