• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 230
  • Last Modified:

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.
0
ManionG
Asked:
ManionG
1 Solution
 
sognoctCommented:
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

0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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