Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

How do I sort Objects in an ArrayList

Posted on 2004-08-30
6
Medium Priority
?
244 Views
Last Modified: 2010-04-23
My objects contains 2 fields, a date and a text field. They are stored in an ArrayList.  I need to sort on the date field. Can someone show the code to do this? thanks
0
Comment
Question by:rangers99
6 Comments
 
LVL 37

Accepted Solution

by:
gregoryyoung earned 500 total points
ID: 11929654
From MSDN you would make an IComparer class

Imports System
Imports System.Collections
Imports Microsoft.VisualBasic

Public Class SamplesArrayList

   Public Class myReverserClass
      Implements IComparer

      ' Calls CaseInsensitiveComparer.Compare with the parameters reversed.
      Public Function Compare( ByVal x As Object, ByVal y As Object) As Integer _
         Implements IComparer.Compare
         Return New CaseInsensitiveComparer().Compare(y, x)
      End Function 'IComparer.Compare

   End Class 'myReverserClass

   Public Shared Sub Main()

      ' Creates and initializes a new ArrayList.
      Dim myAL As New ArrayList()
      myAL.Add("The")
      myAL.Add("quick")
      myAL.Add("brown")
      myAL.Add("fox")
      myAL.Add("jumps")
      myAL.Add("over")
      myAL.Add("the")
      myAL.Add("lazy")
      myAL.Add("dog")

      ' Displays the values of the ArrayList.
      Console.WriteLine("The ArrayList initially contains the following values:")
      PrintIndexAndValues(myAL)

      ' Sorts the values of the ArrayList using the default comparer.
      myAL.Sort()
      Console.WriteLine("After sorting with the default comparer:")
      PrintIndexAndValues(myAL)

      ' Sorts the values of the ArrayList using the reverse case-insensitive comparer.
      Dim myComparer = New myReverserClass()
      myAL.Sort(myComparer)
      Console.WriteLine("After sorting with the reverse case-insensitive comparer:")
      PrintIndexAndValues(myAL)

   End Sub 'Main

   Public Shared Sub PrintIndexAndValues(myList As IEnumerable)

      Dim i As Integer = 0
      Dim myEnumerator As System.Collections.IEnumerator = myList.GetEnumerator()
      While myEnumerator.MoveNext()
         Console.WriteLine(ControlChars.Tab + "[{0}]:" + ControlChars.Tab + "{1}", i, myEnumerator.Current)
         i += 1
      End While
      Console.WriteLine()

   End Sub 'PrintIndexAndValues

End Class 'SamplesArrayList


'This code produces the following output.
'The ArrayList initially contains the following values:
'        [0]:    The
'        [1]:    quick
'        [2]:    brown
'        [3]:    fox
'        [4]:    jumps
'        [5]:    over
'        [6]:    the
'        [7]:    lazy
'        [8]:    dog
'
'After sorting with the default comparer:
'        [0]:    brown
'        [1]:    dog
'        [2]:    fox
'        [3]:    jumps
'        [4]:    lazy
'        [5]:    over
'        [6]:    quick
'        [7]:    the
'        [8]:    The
'
'After sorting with the reverse case-insensitive comparer:
'        [0]:    the
'        [1]:    The
'        [2]:    quick
'        [3]:    over
'        [4]:    lazy
'        [5]:    jumps
'        [6]:    fox
'        [7]:    dog
'        [8]:    brown



your class for comparing by date would look like ...

   Public Class myCompareClass
      Implements IComparer

      Public Function Compare( ByVal x As Object, ByVal y As Object) As Integer _
         Implements IComparer.Compare
         dim foo as MyObject = CType(x, MyObject)
         dim bar as MyOject = Ctype(y,MyObject)
         return foo.MyDateField.CompareTo(bar.MyDateField)
      End Function 'IComparer.Compare

   End Class

you could also just implement IComparable on your class to compare the two date fields if this is always how you want them sorted.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemicomparableclasstopic.asp

Public Class Temperature
    Implements IComparable

    Public Overloads Function CompareTo(ByVal obj As Object) As Integer _
        Implements IComparable.CompareTo

        If TypeOf obj Is Temperature Then
            Dim temp As Temperature = CType(obj, Temperature)

            Return m_value.CompareTo(temp.m_value)
        End If

        Throw New ArgumentException("object is not a Temperature")
    End Function

    ' The value holder
    Protected m_value As Integer

    Public Property Value() As Integer
        Get
            Return m_value
        End Get
        Set(ByVal Value As Integer)
            m_value = Value
        End Set
    End Property

    Public Property Celsius() As Integer
        Get
            Return (m_value - 32) / 2
        End Get
        Set(ByVal Value As Integer)
            m_value = Value * 2 + 32
        End Set
    End Property
End Class

is an example of this ... when you do that, the object will sort using the default Sort.
0
 
LVL 10

Expert Comment

by:prakash_prk
ID: 11929756
0
 
LVL 37

Expert Comment

by:gregoryyoung
ID: 11929774
googling ? thats in java :)
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 10

Expert Comment

by:prakash_prk
ID: 11931015
Oh I am sorry .
0
 
LVL 8

Expert Comment

by:wguerram
ID: 11932623
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 11936116
Why don't you use a SortedList object instead?

Bob
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction When many people think of the WebBrowser (http://msdn.microsoft.com/en-us/library/2te2y1x6%28v=VS.85%29.aspx) control, they immediately think of a control which allows the viewing and navigation of web pages. While this is true, it's a…
1.0 - Introduction Converting Visual Basic 6.0 (VB6) to Visual Basic 2008+ (VB.NET). If ever there was a subject full of murkiness and bad decisions, it is this one!   The first problem seems to be that people considering this task of converting…
Integration Management Part 2
Screencast - Getting to Know the Pipeline
Suggested Courses
Course of the Month10 days, 17 hours left to enroll

885 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question