Hi,
Please find below a class that you can use to sort a collection of any
type, the sorted type has to implement nothing.
You may use it like this:
ArrayList.Sort( new ClassSorter( "PropertyNameToCompareBy",
SortDirection.Ascending ) );
It's very simple it use reflection to get the value of
PropertyNameToCompareBy which needs to be an IComparable.
A good thing of the shown implementation is that the property may be a
complex type and you can sort by something like:
"TopProperty.InnerProperty"
The class will see that TopProperty has a property and will descend to get
its value.
Hope this help,
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
//*********************** Start of the Code ************/
public class ClassSorter: IComparer
{
protected string sortBy;
protected SortDirection sortDirection;
#region Constructors
public ClassSorter(string sortBy, SortDirection
sortDirection)
{
this.sortBy = sortBy;
this.sortDirection = sortDirection;
}
#endregion
int Compare( object x, object y, string comparer)
{
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 SortDirection
{
Ascending = 0,
Descending = 1
}
//*********************** End of the Code ************/
"ryba" <ba******@poczta.onet.pl> wrote in message
news:br**********@atlantis.news.tpi.pl...
Hello
I'm sorry for mistakes - my English isn't very well.
I've got the problem with sorting objects in ArrayList. If I put there
only strings, Sort method works great, but it doesnt work when I put there
objects (even if ToString method is override in object class).
I think that i have to override a comparator in my object class, but even
if it is correc I dont know how to do it...
I'd be very greatfull if Somebody could help me.