How do I sort an ArrayList of objects by a property value

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Paulers

    How do I sort an ArrayList of objects by a property value

    Hello I have an ArrayList full of Person objects. I would like to sort
    the object array by the objects property 'Name' so when I loop through
    it and populate a combobox they are in order. How do I attack something
    like this? Any help is greatly appreciated.

    thanks!

  • hoppy

    #2
    Re: How do I sort an ArrayList of objects by a property value

    "Paulers" <SuperGh0d@gmai l.comwrote in
    news:1167350973 .191094.3620@48 g2000cwx.google groups.com:
    Hello I have an ArrayList full of Person objects. I would like to sort
    the object array by the objects property 'Name' so when I loop through
    it and populate a combobox they are in order. How do I attack
    something like this? Any help is greatly appreciated.
    >
    thanks!
    >
    >

    Make the person class implement the IComparable interface, Write code
    for the Compare method that appears. Then it will all magically work
    when you call the sort method. If this is a 2005 version then you can
    use IComparable(Of Person). And use a list(Of Person) instead of
    arraylist too!

    If you have 2003, then change this to plain IComparable. The parameter
    of the Compare method will be an object, so cast it to Person.

    Public Class Person
    Implements IComparable(Of Person)

    Private _name As String

    Public Property Name() As String
    Get
    Return _name
    End Get
    Set(ByVal value As String)
    _name = value
    End Set
    End Property

    ' called by the arraylist.sort method.
    Public Function CompareTo(ByVal other As Person) As Integer _
    Implements System.ICompara ble(Of Person).Compare To
    ' Compare this ones name with the other ones name.
    ' return <0 if this one comes first,
    ' 0 if they are equal,
    ' >0 if the other one comes first.
    ' String.Compare does this anyway
    Return String.Compare( Me.Name, other.Name)
    End Function
    End Class

    Comment

    • =?Utf-8?B?S2VycnkgTW9vcm1hbg==?=

      #3
      RE: How do I sort an ArrayList of objects by a property value

      Paulers,

      One way is to have your Person class implement IComparable.Com pareTo. For
      Example:

      Public Class Person
      Implements IComparable

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

      Dim person As Person = DirectCast(obj, Person)

      If Me.Name < person.Name Then
      Return -1
      ElseIf Me.Name = person.Name Then
      Return 0
      Else
      Return 1
      End If
      End Function

      Then, when you call the arraylist's Sort method, the objects will be sorted
      by Name.

      "Paulers" wrote:
      Hello I have an ArrayList full of Person objects. I would like to sort
      the object array by the objects property 'Name' so when I loop through
      it and populate a combobox they are in order. How do I attack something
      like this? Any help is greatly appreciated.
      >
      thanks!
      >
      >

      Comment

      • Herfried K. Wagner [MVP]

        #4
        Re: How do I sort an ArrayList of objects by a property value

        "Paulers" <SuperGh0d@gmai l.comschrieb:
        Hello I have an ArrayList full of Person objects. I would like to sort
        the object array by the objects property 'Name' so when I loop through
        it and populate a combobox they are in order. How do I attack something
        like this?
        <URL:http://dotnet.mvps.org/dotnet/samples/techniques/CompareOperator .zip>

        --
        M S Herfried K. Wagner
        M V P <URL:http://dotnet.mvps.org/>
        V B <URL:http://dotnet.mvps.org/dotnet/faqs/>

        Comment

        • =?Utf-8?B?QWxpZW4yXzUx?=

          #5
          RE: How do I sort an ArrayList of objects by a property value

          Here's how I've done it.. If ArrayList implements the IBindingList interface
          you can use something like this... If it doesn't you can implement the
          IBindingList interface in one of your base classes, if you want an example of
          how to do that look at Rocky Lhotka's CSLA object framework, it's open
          source... Or just use his base classes, it takes a little bit more time to
          implement but it's worth it with the funtionality you achieve by doing so,
          there's also some code generation tools that make generating these object
          hiearchies trivial..

          Public WriteOnly Property Sort() As String

          Set(ByVal Value As String)
          Dim str() As String = Split(Value, " ")
          Dim mSortPropertyNa me As String = "", mSortDirection As String =
          ""

          'parse the input string
          If str.Length = 1 Then 'direction not specified, use default
          mSortPropertyNa me = str(0).Trim
          ElseIf str.Length = 2 Then
          mSortPropertyNa me = str(0).Trim & ""
          mSortDirection = str(1).Trim & ""
          Else
          Throw New ApplicationExce ption("Too many parameters
          specified for the sort.")
          End If
          Dim childType As Type = GetType(Me)
          Dim mSortProperty As PropertyDescrip tor = _

          TypeDescriptor. GetProperties(c hildType).Item( mSortPropertyNa me)
          Select Case mSortDirection. ToUpper.Trim
          Case Is = "DESC"
          DirectCast(Me, IBindingList).A pplySort(mSortP roperty,
          ListSortDirecti on.Descending)
          Case Is = "ASC"
          DirectCast(Me, IBindingList).A pplySort(mSortP roperty,
          ListSortDirecti on.Ascending)
          Case Else
          DirectCast(Me, IBindingList).A pplySort(mSortP roperty,
          ListSortDirecti on.Ascending)
          End Select
          End Set
          End Property


          HTH

          "Paulers" wrote:
          Hello I have an ArrayList full of Person objects. I would like to sort
          the object array by the objects property 'Name' so when I loop through
          it and populate a combobox they are in order. How do I attack something
          like this? Any help is greatly appreciated.
          >
          thanks!
          >
          >

          Comment

          • Chris Dunaway

            #6
            Re: How do I sort an ArrayList of objects by a property value

            Kerry Moorman wrote:
            One way is to have your Person class implement IComparable.Com pareTo. For
            Example:
            >
            Public Class Person
            Implements IComparable
            >
            Public Overloads Function CompareTo(ByVal obj As Object) As Integer _
            Implements IComparable.Com pareTo
            >
            Dim person As Person = DirectCast(obj, Person)
            >
            If Me.Name < person.Name Then
            Return -1
            ElseIf Me.Name = person.Name Then
            Return 0
            Else
            Return 1
            End If
            End Function
            >
            Then, when you call the arraylist's Sort method, the objects will be sorted
            by Name.
            Assuming the Name property is a String, you can shorten that code to
            this:

            Public Class Person
            Implements IComparable

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

            Dim person As Person = DirectCast(obj, Person)

            Return Me.Name.Compare To(person.Name)

            End Function

            Comment

            • Chris Dunaway

              #7
              Re: How do I sort an ArrayList of objects by a property value

              Kerry Moorman wrote:
              Chris,
              >
              That's really nice. I had not noticed that CompareTo method of a string.
              >
              That should work for all primitive types. Of course if you have custom
              comparison logic, such as last name AND first name, then you would have
              to implement like you showed.

              Cheers!

              Chris

              Comment

              • Paulers

                #8
                Re: How do I sort an ArrayList of objects by a property value

                Thanks everyone! I really appreciate your help.
                Chris Dunaway wrote:
                Kerry Moorman wrote:
                Chris,

                That's really nice. I had not noticed that CompareTo method of a string.
                >
                That should work for all primitive types. Of course if you have custom
                comparison logic, such as last name AND first name, then you would have
                to implement like you showed.
                >
                Cheers!
                >
                Chris

                Comment

                Working...