Sorting Arraylists Twice
-
I have a class called tasks and right now it uses compareto to sort by duedate when it is in an arraylist, that is fine for right now, but I'm expanding to group by category. I now want to sort by category and then sort by duedate within the category sort. Is this possible? Here's my class:
public class Task: IComparable { private int _importance; public int Importance { get { return _importance; } set { _importance = value; } } private DateTime _DueDate; public DateTime DueDate { get { return _DueDate; } set { _DueDate = value; } } private string _subject; public string Subject { get { return _subject; } set { _subject = value; } } private string _entryID; public string EntryID { get { return _entryID; } set { _entryID = value; } } private string _category; public string Category { get { return _category; } set { _category = value; } } public int CompareTo(object other) { return _DueDate.CompareTo(((Task)other)._DueDate); } }
-
I have a class called tasks and right now it uses compareto to sort by duedate when it is in an arraylist, that is fine for right now, but I'm expanding to group by category. I now want to sort by category and then sort by duedate within the category sort. Is this possible? Here's my class:
public class Task: IComparable { private int _importance; public int Importance { get { return _importance; } set { _importance = value; } } private DateTime _DueDate; public DateTime DueDate { get { return _DueDate; } set { _DueDate = value; } } private string _subject; public string Subject { get { return _subject; } set { _subject = value; } } private string _entryID; public string EntryID { get { return _entryID; } set { _entryID = value; } } private string _category; public string Category { get { return _category; } set { _category = value; } } public int CompareTo(object other) { return _DueDate.CompareTo(((Task)other)._DueDate); } }
Try this:
public int CompareTo(object value)
{
Task compObj = (Task) value;
int result = _category.CompareTo(compObj._category);
// Check if instances don't differ in their Category.
if (result == 0)
result = _DueDate.CompareTo(compObj._DueDate);
return result;
}