C#:
using IdeaBlade.Persistence;
using IdeaBlade.Util;
/// <summary>
///
Arbitrary n-column sort
/// </summary>
/// <remarks>This
version works with all properties: simple, calculated, nested.</remarks>
public class MultiPropertyComparer<T> where T:
Entity : IComparer<T> {
public MultiPropertyComparer(BindableList<SortProperty<T>> pSortProperties) {
mSortProperties = pSortProperties;
}
public int Compare(T x, T y) {
int retVal
= 0;
if (x.IsNullEntity & y.IsNullEntity) {
//Both are null; don't change their order
retVal
= 0;
}
else if (x.IsNullEntity & ! y.IsNullEntity) {
//x is null and y is not; make x first
retVal
= -1;
}
else if (! x.IsNullEntity & y.IsNullEntity) {
//y is null and x is not; make y first
retVal
= 1;
}
else {
//Neither is null; do the comparison
foreach (SortProperty<T> aSortProperty in mSortProperties) {
IdeaBlade.Util.PropertyComparer<T> comparer
= new IdeaBlade.Util.PropertyComparer<T>(aSortProperty.Descriptor,
aSortProperty.Direction);
retVal = comparer.Compare(x, y);
if (retVal
!= 0) {
break;
}
}
}
return retVal;
}
#region Private Fields
private BindableList<SortProperty<T>> mSortProperties;
#endregion
}
VB.NET:
Imports IdeaBlade.Persistence
Imports IdeaBlade.Util
''' <summary>
''' Arbitrary n-column sort
''' </summary>
''' <remarks>This version works with
all properties: simple, calculated,
nested.</remarks>
Public Class MultiPropertyComparer(Of T As Entity)
Implements IComparer(Of T)
Public Sub New(ByVal pSortProperties As BindableList(Of SortProperty(Of T)))
mSortProperties = pSortProperties
End Sub
Public Function Compare(ByVal x As T, ByVal y As T) As Integer _
Implements System.Collections.Generic.IComparer(Of T).Compare
Dim retVal As Integer
If x.IsNullEntity And y.IsNullEntity Then
'Both are null;
don't change their order
retVal = 0
ElseIf x.IsNullEntity And Not y.IsNullEntity Then
'x is null and
y is not; make x first
retVal = -1
ElseIf Not x.IsNullEntity And y.IsNullEntity Then
'y is null and
x is not; make y first
retVal = 1
Else
'Neither is null;
do the comparison
For Each aSortProperty As SortProperty(Of T) In mSortProperties
Dim comparer As New IdeaBlade.Util.PropertyComparer(Of T)
_
(aSortProperty.Descriptor, aSortProperty.Direction)
retVal = comparer.Compare(x, y)
If retVal <> 0 Then
Exit For
End If
Next
End If
Return retVal
End Function
#Region "Private Fields"
Private mSortProperties As BindableList(Of SortProperty(Of T))
#End Region
End Class
|