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:
Public Class PropertyIComparer
Implements IComparer
Dim _propertyName As String
<DebuggerHidden()> _
Sub New(ByVal propertyName As String)
Me._propertyName = propertyName
End Sub
<DebuggerHidden()> _
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
Dim xObj As Object
Dim yObj As Object
If x.GetType IsNot y.GetType Then
Throw New ArgumentException("Cannot compare two elements with different types in the array.")
End If
Dim pInfo As System.Reflection.PropertyInfo
pInfo = x.GetType.GetProperty(Me._propertyName)
If pInfo Is Nothing Then
Throw New ArgumentException(x.GetType.Name & " doesn't have property named " & Me._propertyName, "propertyName")
End If
xObj = pInfo.GetValue(x, Nothing)
yObj = y.GetType.GetProperty(Me._propertyName).GetValue(y, Nothing)
Dim mInfo As System.Reflection.MethodInfo
mInfo = xObj.GetType.GetMethod("CompareTo", New Type() {xObj.GetType})
If mInfo Is Nothing Then
Throw New ArgumentException(x.GetType.Name & " doesn't Implement IComparable interface.")
End If
Return CInt(mInfo.Invoke(xObj, New Object() {yObj}))
End Function
End Class
And this is how to use it:
vb Code:
Array.Sort(myArray, New PropertyIComparer("Property_Name"))