Great example of sorting a Generic.List
////// The generic comparer class allows for sorting on a generic collections property fields /// ///An object public class GenericComparer : IComparer { /// /// Creates a new instance of the GenericComparer class /// /// A string expression of the field to sort /// A SortDirection value to indicate /// Ascending or Descending sort public GenericComparer(string sortExpression, SortDirection sortDirection) { this.SortExpression = sortExpression; this.SortDirection = sortDirection; } ////// Private container for the Sort Direction /// private SortDirection sortDirection; ////// Private container for the expression used for the sort /// private string sortExpression; ////// The expression to use during the sort (in this case, the Generic objects field name) /// public string SortExpression { get { return sortExpression; } set { sortExpression = value; } } ////// The direction to perform the sort /// public SortDirection SortDirection { get { return this.sortDirection; } set { this.sortDirection = value; } } ////// Performs the sort on the supplied objects /// ////// The following example shows how to implement and use this class: /// items = MyDataObject.GetObjects(); /// items.Sort(new GenericComparer(SortExpression, SortDirection)); /// } /// } /// ]]> /// /// The first object /// The second object ///An int value that specifies the result of the comparison public int Compare(T x, T y) { PropertyInfo propertyInfo = typeof(T).GetProperty(SortExpression); IComparable obj1 = (IComparable)propertyInfo.GetValue(x, null); IComparable obj2 = (IComparable)propertyInfo.GetValue(y, null); if (SortDirection == SortDirection.Ascending) return obj1.CompareTo(obj2); else return obj2.CompareTo(obj1); } }







2 Responses
Bitstar
December 5th, 2008 at 2:33 am
1Thanks for the code. It saved me a ton of research today.
Wayne
December 5th, 2008 at 9:47 am
2Wow, that only took one year to help someone! hahaha, glad you found it useful.
Follow Wayne John
Categories
Archives
Websites by Wayne
Recent Posts
Tag Cloud