Sorting ArrayList of Integers

Hi there,

I have an ArrayList (al) containg integers. When I use al.Sort() i want items to be properly ordered.

Instead of results like this: 1, 2, 3, 10, 12, 16, 23 (would be good)
I get results like this: 1, 10, 12, 16, 2, 23, 3 (is bad)

How do I do it?

Yours,

Johan


11loginAsked:
Who is Participating?
 
VBRocksCommented:
Here's an example of how you can do it:

    Private Sub SortItems()

        Dim list As New System.Collections.Generic.List(Of System.Int32)

        'Add your items here
        list.AddRange(New Int32() {1, 10, 12, 16, 2, 23, 3})

        list.Sort(AddressOf SortList)

        For Each i As System.Int32 In list
            PrintResults(i)
        Next

    End Sub

    Private Function SortList(ByVal x As System.Int32, _
        ByVal y As System.Int32) As Integer

        Return x.CompareTo(y)

    End Function


    Private Sub PrintResults(ByVal i As System.Int32)
        System.Diagnostics.Debug.Print(i.ToString())

    End Sub

0
 
jasonclarkeCommented:
Can you post some code?  ArrayList.Sort should work as expected.
0
 
Bob LearnedCommented:
It looks like you have strings, and not integers in the array.

Bob
0
 
11loginAuthor Commented:
Yikes, that was embarrasing... this was the code:
   
Dim alCount As New ArrayList
For Each iValue As String hCount.Values()
      alCount.Add(iValue)
Next
alCount.Sort()

I actually added the values as strings, although there where integers in the hashtable. I made the change and it works now (of course). Thanks a lot, all of you!

/Johan
0
 
jasonclarkeCommented:
I suppose this is actually a good example of why using generics is a good thing - the compiler would have spotted this mistake.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.