Home All Groups Group Topic Archive Search About

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

Author
29 Dec 2006 12:09 AM
Paulers
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!

Author
29 Dec 2006 12:38 AM
hoppy
"Paulers" <SuperG***@gmail.com> wrote in
news:1167350973.191094.3620@48g2000cwx.googlegroups.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.IComparable(Of Person).CompareTo
      ' 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
Are all your drivers up to date? click for free checkup

Author
29 Dec 2006 12:45 AM
Kerry Moorman
Paulers,

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

Public Class Person
    Implements IComparable

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

        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.

Show quoteHide quote
"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!
>
>
Author
29 Dec 2006 5:15 PM
Chris Dunaway
Kerry Moorman wrote:

Show quoteHide quote
> One way is to have your Person class implement IComparable.CompareTo.  For
> Example:
>
> Public Class Person
>     Implements IComparable
>
>     Public Overloads Function CompareTo(ByVal obj As Object) As Integer _
>     Implements IComparable.CompareTo
>
>         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.CompareTo

        Dim person As Person = DirectCast(obj, Person)

        Return Me.Name.CompareTo(person.Name)

    End Function
Author
29 Dec 2006 5:31 PM
Kerry Moorman
Chris,

That's really nice. I had not noticed that CompareTo method of a string.

Thanks for the info.

Kerry Moorman


Show quoteHide quote
"Chris Dunaway" wrote:

>
> 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.CompareTo
>
>         Dim person As Person = DirectCast(obj, Person)
>
>         Return Me.Name.CompareTo(person.Name)
>
>     End Function
>
>
Author
29 Dec 2006 10:00 PM
Chris Dunaway
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
Author
31 Dec 2006 7:10 AM
Paulers
Thanks everyone! I really appreciate your help.
Chris Dunaway wrote:
Show quoteHide quote
> 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
Author
29 Dec 2006 12:47 AM
Herfried K. Wagner [MVP]
"Paulers" <SuperG***@gmail.com> schrieb:
> 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/>
Author
29 Dec 2006 12:50 AM
Alien2_51
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 mSortPropertyName As String = "", mSortDirection As String =
""

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

TypeDescriptor.GetProperties(childType).Item(mSortPropertyName)
            Select Case mSortDirection.ToUpper.Trim
                Case Is = "DESC"
                    DirectCast(Me, IBindingList).ApplySort(mSortProperty,
ListSortDirection.Descending)
                Case Is = "ASC"
                    DirectCast(Me, IBindingList).ApplySort(mSortProperty,
ListSortDirection.Ascending)
                Case Else
                    DirectCast(Me, IBindingList).ApplySort(mSortProperty,
ListSortDirection.Ascending)
            End Select
        End Set
    End Property


HTH

Show quoteHide quote
"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!
>
>

Bookmark and Share

Post Thread options