[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 810
  • Last Modified:

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


0
11login
Asked:
11login
3 Solutions
 
jasonclarkeCommented:
Can you post some code?  ArrayList.Sort should work as expected.
0
 
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
 
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

Featured Post

Veeam and MySQL: How to Perform Backup & Recovery

MySQL and the MariaDB variant are among the most used databases in Linux environments, and many critical applications support their data on them. Watch this recorded webinar to find out how Veeam Backup & Replication allows you to get consistent backups of MySQL databases.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now