Link to home
Start Free TrialLog in
Avatar of ManionG
ManionG

asked on

Sorting an arrayList

I have an arrayList where each object has an int and a float.
I populate this list from data pairs and I wish to sort the arrayList by the floating point value field. The purpose is enable me to locate the associated int values for each of the sorted floats.

Am I using the correct data structure or is there a better alternative?
GM.
ASKER CERTIFIED SOLUTION
Avatar of Rahul Gupta
Rahul Gupta
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sognoct
Here there is an example (I used array of object instead of array list) , you didn't say if you are working on vb.net or csharp ... so I wrote the example in vb for csharp version just ask ...

Private Sub btnOrder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOrder.Click
    Dim o() As myObject = New myObject() {New myObject(1, 9.2), New myObject(2, 8.223), New myObject(4, 10.56), New myObject(5, 5.73)}
    Dim com As New clsInfoComparer
    Array.Sort(o, com)
    For Each m As myObject In o
      Console.WriteLine(m.val1.ToString & " " & m.val2.ToString)
    Next

  End Sub

  Public Class myObject
    Public val1 As Int32
    Public val2 As Double
    Public Sub New(ByVal v1 As Int32, ByVal v2 As Double)
      val1 = v1
      val2 = v2
    End Sub
  End Class

  Public Class clsInfoComparer
    Implements IComparer

    Function Compare(ByVal x As [Object], ByVal y As [Object]) As Integer Implements IComparer.Compare
      Dim t1, t2 As myObject
      t1 = CType(x, myObject)
      t2 = CType(y, myObject)
      If (t1.val2 > t2.val2) Then
        Return 1
      End If

      If (t1.val2 < t2.val2) Then
        Return -1
      Else
        Return 0
      End If
    End Function 'IComparer.Compare
  End Class 'myReverserClass

Open in new window