Tag Archives: Sort

Sorting a generic List object by passing an IComparer object to the Sort method doesn’t preserve order of items that are equal.

List<ArtifactDetails> recordset = GetArtifactsFromProvider();
recordset.Sort(new Core.Comparer<ArtifactDetails>(sortExpression));

http://msdn.microsoft.com/en-us/library/234b841s(VS.80).aspx

This method uses System.Array.Sort, which uses the QuickSort algorithm. This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.

http://www.csharp411.com/c-stable-sort/

http://en.wikipedia.org/wiki/Stable_sort#Classification

What are our options if we want a stable sort?

  • Write our own sort algorithm that is a stable sort so that the original order is preserved. There are several n log n sorts that are stable sorts; they take more memory than the QuickSort though.

Or if we don’t want the order to change if the sortExpression was empty?

  • Check for an empty string and use a default sort order like uid or whatever the primary key is.
  • Check sortExpression for an empty string and just not call sort.
  • Write a SortList function that does the checking for an empty sortExpression.
protected static List<T> SortList<T>(List<T> list, string sortExpression)
{
    if (!string.IsNullOrEmpty(sortExpression)) list.Sort(new Core.Comparer<T>(sortExpression));
    return list;
}

Then instead of using the Sort call at the top of this post use this call.

List<ArtifactDetails> recordset = GetArtifactsFromProvider();
recordset = SortList(recordset, sortExpression);

Are there other better options? Maybe, but this gets the job done without a lot of extra code.