This isn't necessarily answering the original question, but it somewhat extends some of the possibilities outlined. I am posting this in case others come across the similar problem.
The solution posted here outlines a generic order by option that may be useful in other cases. In this example, I wanted to sort a file list by different properties.
/// <summary>
/// Used to create custom comparers on the fly
/// </summary>
/// <typeparam name="T"></typeparam>
public class GenericCompare<T> : IComparer<T>
{
// Function use to perform the compare
private Func<T, T, int> ComparerFunction { set; get; }
// Constructor
public GenericCompare(Func<T, T, int> comparerFunction)
{
ComparerFunction = comparerFunction;
}
// Execute the compare
public int Compare(T x, T y)
{
if (x == null || y == null)
{
// These 3 are bell and whistles to handle cases where one of the two is null, to sort to top or bottom respectivly
if (y == null && x == null) { return 0; }
if (y == null) { return 1; }
if (x == null) { return -1; }
}
try
{
// Do the actual compare
return ComparerFunction(x, y);
}
catch (Exception ex)
{
// But muffle any errors
System.Diagnostics.Debug.WriteLine(ex);
}
// Oh crud, we shouldn't be here, but just in case we got an exception.
return 0;
}
}
Then in the implementation…
GenericCompare<FileInfo> DefaultComparer;
if (SortOrder == SORT_FOLDER_FILE)
{
DefaultComparer = new GenericCompare<FileInfo>((fr1, fr2) =>
{
return fr1.FullName.ToLower().CompareTo(fr2.FullName.ToLower());
});
}
else if (SortOrder == SORT_SIZE_ASC)
{
DefaultComparer = new GenericCompare<FileInfo>((fr1, fr2) =>
{
return fr1.Length.CompareTo(fr2.Length);
});
}
else if (SortOrder == SORT_SIZE_DESC)
{
DefaultComparer = new GenericCompare<FileInfo>((fr1, fr2) =>
{
return fr2.Length.CompareTo(fr1.Length);
});
}
else
{
DefaultComparer = new GenericCompare<FileInfo>((fr1, fr2) =>
{
return fr1.Name.ToLower().CompareTo(fr2.Name.ToLower());
});
}
var ordered_results = (new DirectoryInfo(@"C:\Temp"))
.GetFiles()
.OrderBy(fi => fi, DefaultComparer);
The big advantage is that you then don’t need to create a new class for each order by case, you can just wire up a new lambda. Obviously this can be extended in all sorts of ways, so hopefully it will helps someone, somewhere, sometime.