using icomparable

  • Thread starter Thread starter soni2926
  • Start date Start date
S

soni2926

hi,
I have a class called orders, which has a DateTime dateCreated
property, telling me when each order was created. I get the orders
returned to me in a collection, as an array. but now i need to sort
them by datecreated. i've tried the following:
// implement IComparable
public class ProjOrderHistory : IComparable
{
public DateTime dateCreated;
....
public int CompareTo(object obj)
{
OrderHistorySummary temp = (OrderHistorySummary)obj;
return
this.dateCreated.CompareTo(temp.dateCreated);
}
}

and when i build it i get back an ProjOrderHistory [] object called
_orders. Now _orders is populating fine with the order information,
but when i try to call
Array.Sort(_orders)
i get "Expression has been evaluated and has no value"
am i missing something, or is my CompareTo wrong?

Thanks.
 
Sorry the compareTo should be like this:
public int CompareTo(object obj)
{
ProjOrderHistory temp = (ProjOrderHistory)obj;
return
this.dateCreated.CompareTo(temp.dateCreated);
}
 
Where do you get that message? As an exception? Or when you call
Array.Sort in the immediate window?

Have you looked to see if you data is now sorted? Array.Sort does an
in-place sort on the array you pass it - and it looks like it should
be fine. Another point; if DateCreated isn't the *natural* sequence
for this object, then personally I would tend to *not* implement
IComparable, and use an external IComparer / IComparer<T> /
Comparison<T> - e.g. (of the latter):

Array.Sort(_orders, delegate(ProjOrderHistory lhs,
ProjOrderHistory rhs) {
return DateTime.Compare(lhs.DateCreated, rhs.DateCreated);
});
 
Back
Top