Sorting

  • Thread starter Thread starter Nikolay Petrov
  • Start date Start date
N

Nikolay Petrov

I have a function which returns ArrayList of classes
my retrun class looks something like this

Public Class TestClass
Public Str1 as String
Public Int1 as Integer
Public Str2 as String
End Class

Is it possible to sort the items in the ArrayList by one of these
public variables?

If yes, any sample code will be helpfull.

Thanks
 
Nikolay,
The "easiest" way is to use a Comparer object.

Here's a relatively generic Comparer object.

Imports System.ComponentModel

Protected Class PropertyComparer
Implements IComparer

Private ReadOnly m_property As PropertyDescriptor
Private ReadOnly m_ascending As Boolean

Public Sub New(ByVal componentType As Type, _
ByVal propertyName As String, ByVal ascending As Boolean)
Dim properties As PropertyDescriptorCollection
properties = TypeDescriptor.GetProperties(componentType)
m_property = properties(propertyName)
m_ascending = ascending
End Sub

Private Function Compare(ByVal x As Object, ByVal y As Object) _
As Integer Implements IComparer.Compare
x = m_property.GetValue(x)
y = m_property.GetValue(y)
If m_ascending Then
Return New CaseInsensitiveComparer().Compare(x, y)
Else
Return New CaseInsensitiveComparer().Compare(y, x)
End If
End Function

End Class

Dim list As ArrayList
Dim mycomparer As New PropertyComparer(GetType(TestClass), col,
True)
list.Sort(mycomparer)

Note PropertyComparer requires that you use Properties instead of Fields in
your class:
Public Class TestClass Private m_str1 As String
Public Property Str1 as String
Get
Return m_str1
End Get
Set(value As String)
m_str1 = value
End Set
End Property
Public Property Int1 as Integer
Public Property Str2 as String
End Class

Using Properties allows the value to be "Better" encapsulated.

Hope this helps
Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top