GenericComparer<Address> comparer = new GenericComparer<Address>() .OrderBy("FirstName, LastName DESC");
public class GenericComparer<T> : IComparer<T>{ Type declaringClassType = typeof(T); IList<PropertyOrderBy> properties = new List<PropertyOrderBy>(); /// <summary> /// Default ctor instantiates a new GenericComparer instance. /// </summary> public GenericComparer() { } public GenericComparer<T> OrderBy(string sqlOrderBy) { string[] parts = sqlOrderBy.Split(','); foreach (string part in parts) { string[] orderbyParts = part.Trim().Split(' '); string fieldName = orderbyParts[0].Trim(); string direction = string.Empty; if (orderbyParts.Length > 1) direction = orderbyParts[1].Trim(); properties.Add(new PropertyOrderBy(fieldName, direction)); } return this; } private IComparable GetPropertyValue(object instance, string propertyName) { // This won't work if the property is overloaded by type PropertyInfo info = declaringClassType.GetProperty(propertyName); object val = info.GetValue(instance, null); IComparable retVal = val as IComparable; if (retVal == null) { throw new ApplicationException( propertyName + " Type must implement IComparable to be able to use a PropertyComparer."); } return retVal; } #region IComparer<T> Members public int Compare(T lhsObj, T rhsObj) { int result = 0; foreach (PropertyOrderBy orderBy in properties) { IComparable lhs = GetPropertyValue(lhsObj, orderBy.PropertyName); IComparable rhs = GetPropertyValue(rhsObj, orderBy.PropertyName); if (orderBy.SortDirection == "DESC") result = rhs.CompareTo(lhs); else result = lhs.CompareTo(rhs); if (result != 0) return result; } return result; } #endregion private class PropertyOrderBy { public string PropertyName; public string SortDirection = "ASC"; public PropertyOrderBy(string propertyName, string direction) { direction = direction.ToUpper(); if (direction != "ASC" && direction != "DESC" && direction != string.Empty) throw new ArgumentOutOfRangeException("direction", "Unknown order by direction: " + direction + ", expected either ASC or DESC."); if (direction != string.Empty) this.SortDirection = direction; this.PropertyName = propertyName; } }}
Powered by: newtelligence dasBlog 2.1.8102.813
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2010, Shawn Neal
E-mail