PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197
ICamparer class to sort an object by its property.-VBForums
Results 1 to 1 of 1

Thread: ICamparer class to sort an object by its property.

  1. #1

    Thread Starter
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    ICamparer class to sort an object by its property.

    I created this class to make it possible to sort an object by its public property. I called the class "PropertyICamparer" which implements System.Collections.IComparer interface.

    Here is the class:
    vb Code:
    1. Public Class PropertyIComparer
    2.     Implements IComparer
    3.  
    4.     Dim _propertyName As String
    5.  
    6.     <DebuggerHidden()> _
    7.     Sub New(ByVal propertyName As String)
    8.         Me._propertyName = propertyName
    9.     End Sub
    10.  
    11.     <DebuggerHidden()> _
    12.     Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
    13.         Dim xObj As Object
    14.         Dim yObj As Object
    15.  
    16.         If x.GetType IsNot y.GetType Then
    17.             Throw New ArgumentException("Cannot compare two elements with different types in the array.")
    18.         End If
    19.         Dim pInfo As System.Reflection.PropertyInfo
    20.         pInfo = x.GetType.GetProperty(Me._propertyName)
    21.         If pInfo Is Nothing Then
    22.             Throw New ArgumentException(x.GetType.Name & " doesn't have property named " & Me._propertyName, "propertyName")
    23.         End If
    24.         xObj = pInfo.GetValue(x, Nothing)
    25.         yObj = y.GetType.GetProperty(Me._propertyName).GetValue(y, Nothing)
    26.         Dim mInfo As System.Reflection.MethodInfo
    27.         mInfo = xObj.GetType.GetMethod("CompareTo", New Type() {xObj.GetType})
    28.         If mInfo Is Nothing Then
    29.             Throw New ArgumentException(x.GetType.Name & " doesn't Implement IComparable interface.")
    30.         End If
    31.         Return CInt(mInfo.Invoke(xObj, New Object() {yObj}))
    32.     End Function
    33.  
    34. End Class
    And this is how to use it:
    vb Code:
    1. Array.Sort(myArray, New PropertyIComparer("Property_Name"))

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width