Solved

How do I sort Objects in an ArrayList

Posted on 2004-08-30
6
237 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 125 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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

This tutorial demonstrates one way to create an application that runs without any Forms but still has a GUI presence via an Icon in the System Tray. The magic lies in Inheriting from the ApplicationContext Class and passing that to Application.Ru…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

743 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now