Hi Mark,
I have another solution, with this you can sort any collection without need
to change anything in the class being sorted. I only use reflection.
A very good thing about it is that you can sort using a property of a
property , if your Person class has a property of type Address you could
sort it by Person.Property.Zip for example.
Here I send you the code. and a brief way of using it.
Hope this help,
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
This is how easy it's to use: ( it's a method of the strong t yped
collection )
public CostCenterCollection Sort( string sortParam, TSRCore.SortDirection
direction)
{
ArrayList newlist = (ArrayList)InnerList.Clone();
ClassSorter sorter = new ClassSorter( sortParam, SortByType.Property,
direction);
newlist.Sort( sorter);
return new CostCenterCollection( newlist); //This is the strong typed
collection class , I return a new sorted instance
}
As you can see it's extremely easy to use.
ClassSorter
------------------------
This class implement the IComparer interface, it use reflection to get the
value, it recieve the name of the property to evaluate in a parameter in the
constructor:
public class ClassSorter: IComparer
{
protected string sortBy;
protected SortByType sortByType;
protected SortDirection sortDirection;
#region Constructors
public ClassSorter(string sortBy, SortByType sortByType, SortDirection
sortDirection)
{
this.sortBy = sortBy;
this.sortByType = sortByType;
this.sortDirection = sortDirection;
}
#endregion
int Compare( object x, object y, string comparer)
{
if ( (x== null ) && (y==null) )
return 0;
if ( x == null )
return -1;
if ( y == null )
return 1;
if ( comparer.IndexOf( ".") != -1 )
{
//split the string
string[] parts = comparer.Split( new char[]{ '.'} );
return Compare( x.GetType().GetProperty( parts[0]).GetValue(x, null) ,
y.GetType().GetProperty( parts[0]).GetValue(y, null) , parts[1]
);
}
else
{
IComparable icx, icy;
icx =
(IComparable)x.GetType().GetProperty( comparer).GetValue(x, null);
icy =
(IComparable)y.GetType().GetProperty( comparer).GetValue(y, null);
if ( x.GetType().GetProperty(comparer).PropertyType ==
typeof(System.String) )
{
icx = (IComparable) icx.ToString().ToUpper();
icy = (IComparable) icy.ToString().ToUpper();
}
if(this.sortDirection == SortDirection.Descending)
return icy.CompareTo(icx);
else
return icx.CompareTo(icy);
}
}
public int Compare(object x, object y)
{
return Compare( x, y, sortBy);
}
}
public enum SortByType
{
Method = 0,
Property = 1
}
public enum SortDirection
{
Ascending = 0,
Descending = 1
}