Sorting
I'm using a custom collection class that I wrote previously to handle these sorting capabilities, mostly because I know how the class works, and so I'm comfortable and don't view it as a risk in my development process. But I don't have the sorting capability, so I have to add that. My collection class implements IList<T>, as well as IComparer<T>, so that whatever type is provided is also provided here. I have a Compare method definition as:
public virtual int Compare(T x, T y)
{
if (x != null && y != null)
return x.ToString().CompareTo(y.ToString());
else if (x != null)
return 1;
else if (y != null)
return -1;
return 0;
}
Basically, the compare method makes sure the object exists, and returns the appropriate integer value. If both exist, the string version of the object is used for comparison. This method is meant to be overridden in derived classes. So, to do sorting, remember that the base object storing the class is a list, so we can use this to sort. The sort method I have defined are:
public void Sort()
{
this.Sort(true);
}
public void Sort(bool ascending)
{
_ascending = ascending;
//Create a new delegate to use the Compare method for sorting
Comparison<T> comparisonDelegate = new Comparison<T>(this.Compare);
//Sort the collection
this.List.Sort(comparisonDelegate);
}
What is nice is the new Comparison object, which stores the delegate of a method of the syntax int(T, T), which is what the Compare method is. Using this, I pass the delegate to the list sort method. How this is useful is that you don't have to worry about sorting; instead, in your derived class, you have to override the Compare method and put in your comparison logic. It's very simple this way; the tests will tell if it works correctly.