Created
March 28, 2014 20:57
-
-
Save ianfnelson/9842860 to your computer and use it in GitHub Desktop.
Code for 2004 blog post A Generic Sorter For Strongly-Typed Collections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Globalization; | |
using System.Reflection; | |
namespace IanNelson.Utilities | |
{ | |
/// <SUMMARY> | |
/// A generic sorter, inheriting from IComparer, | |
/// intended to allow for the sorting of | |
/// strongly-typed collections on any named public property | |
/// which implements IComparable | |
/// </SUMMARY> | |
public class GenericSorter : IComparer | |
{ | |
string sortPropertyName; | |
SortOrder sortOrder; | |
public GenericSorter(string sortPropertyName) | |
{ | |
this.sortPropertyName = sortPropertyName; | |
this.sortDirection = SortDirection.Ascending; | |
// default to ascending order | |
} | |
public GenericSorter(string sortPropertyName, | |
SortDirection sortOrder) | |
{ | |
this.sortPropertyName = sortPropertyName; | |
this.sortDirection = sortDirection; | |
} | |
public int Compare(object x, object y) | |
{ | |
// Get the values of the relevant property on the | |
// x and y objects | |
object valueOfX = x.GetType(). | |
GetProperty(sortPropertyName).GetValue(x, null); | |
object valueOfY = y.GetType(). | |
GetProperty(sortPropertyName).GetValue(y, null); | |
// Do the comparison | |
if (sortOrder == SortOrder.Ascending) | |
{ | |
return ((IComparable)valueOfX).CompareTo(valueOfY); | |
} | |
else | |
{ | |
return ((IComparable)valueOfY).CompareTo(valueOfX); | |
} | |
} | |
} | |
/// | |
/// Enumerator to indicate whether to sort in ascending or | |
/// descending order | |
/// | |
public enum SortDirection | |
{ | |
Ascending, | |
Descending | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment