Need sort comparator help
Hi, I have a sort comparator that I am using to sort a List<> by a DateTime value and a String value. Here is the code:
Code:
public class AppointmentComparer3 : Comparer<MSTSAppointment>
{
public override int Compare(MSTSAppointment x, MSTSAppointment y)
{
if (x.VAttendee == y.VAttendee)
{
return x.StartTime.CompareTo((DateTime)y.StartTime);
}
if (x.StartTime == y.StartTime)
{
return (x.VAttendee.CompareTo((string)y.VAttendee));
}
else return (x.VAttendee.CompareTo((string)y.VAttendee));
}
}
The "VAttendee"'s are the Strings, and the "StartTime"'s are the DateTime values.
Two things I need to accomplish:
1. Increase speed. This is pretty slow when I have a few thousand items to sort. If I comment out the call to the sort (doesn't affect my app's functionality, just the visuals) it's noticeably faster.
2. Modify functionality, so that if the DateTime (StartTime) values are identical, the items are returned in alphabetical order by VAttendee.
I am using VS2008 and .NET 3.5SP1.
I am guessing that sorting by DateTime values is inherently slow, but I don't know this for a fact that's why I'm asking.
Any help is appreciated!
Re: Need sort comparator help
Hi there,
where is the data coming from? If you have the data in the database you can sort it there.
Re: Need sort comparator help
It's not in a database... it's a collection of custom objects, contained in a List<>. If it was contained in a SQL database that's a great idea, but it isn't.
Re: Need sort comparator help
The usual pattern for sorting by multiple properties like this is:
Code:
public int Compare (MyClass left, MyClass right)
{
int result;
if ((result = left.Prop1.CompareTo (right.Prop1)) != 0)
return result;
if ((result = left.Prop2.CompareTo (right.Prop2)) != 0)
return result;
... etc
return 0; // All compared properties were the same.
}