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( "PropertyNameTo CompareBy",
SortDirection.A scending ) );
It's very simple it use reflection to get the value of
PropertyNameToC ompareBy 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.In nerProperty"
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(str ing sortBy, SortDirection
sortDirection)
{
this.sortBy = sortBy;
this.sortDirect ion = sortDirection;
}
#endregion
int Compare( object x, object y, string comparer)
{
if ( comparer.IndexO f( ".") != -1 )
{
//split the string
string[] parts = comparer.Split( new char[]{ '.'} );
return Compare( x.GetType().Get Property( parts[0]).GetValue(x, null) ,
y.GetType().Get Property( parts[0]).GetValue(y, null) , parts[1]
);
}
else
{
IComparable icx, icy;
icx =
(IComparable)x. GetType().GetPr operty( comparer).GetVa lue(x, null);
icy =
(IComparable)y. GetType().GetPr operty( comparer).GetVa lue(y, null);
if ( x.GetType().Get Property(compar er).PropertyTyp e ==
typeof(System.S tring) )
{
icx = (IComparable) icx.ToString(). ToUpper();
icy = (IComparable) icy.ToString(). ToUpper();
}
if(this.sortDir ection == SortDirection.D escending)
return icy.CompareTo(i cx);
else
return icx.CompareTo(i cy);
}
}
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******@poczt a.onet.pl> wrote in message
news:br******** **@atlantis.new s.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.