this.sfGrid.SortComparers.Add(new SortComparer() { Comparer = new CustomComparer(), PropertyName = "Name" });
public class CustomComparer : IComparer<object>, ISortDirection
{
private ListSortDirection _SortDirection;
public ListSortDirection SortDirection
{
get { return _SortDirection; }
set { _SortDirection = value; }
}
public int Compare(object x, object y)
{
int namX;
int namY;
//While data object passed to comparer
if (x.GetType() == typeof(UserInfo))
{
namX = ((UserInfo)x).Name.Length;
namY = ((UserInfo)y).Name.Length;
}
//While sorting groups
else if (x.GetType() == typeof(Group))
{
//Calculating the group key length
namX = ((Group)x).Key.ToString().Length;
namY = ((Group)y).Key.ToString().Length;
}
else
{
namX = x.ToString().Length;
namY = y.ToString().Length;
}
//returns the comparison result based in SortDirection.
if (namX.CompareTo(namY) > 0)
return SortDirection == ListSortDirection.Ascending ? 1 : -1;
else if (namX.CompareTo(namY) == -1)
return SortDirection == ListSortDirection.Ascending ? -1 : 1;
else
return 0;
}
} |