public class MyOrderingClass : IComparer<Order>{public int Compare(Order x, Order y){int compareDate = x.Date.CompareTo(y.Date);if (compareDate == 0){return x.OrderID.CompareTo(y.OrderID);}return compareDate;}}
然后要使用这个IComper类,只需实例化它并将其传递给您的Sort方法:
IComparer<Order> comparer = new MyOrderingClass();orderList.Sort(comparer);
//Get data from database, then sort list by staff name:
List<StaffMember> staffList = staffHandler.GetStaffMembers();
var sortedList = from staffmember in staffListorderby staffmember.Name ascendingselect staffmember;
public List<T> Sort_List<T>(string sortDirection, string sortExpression, List<T> data){
List<T> data_sorted = new List<T>();
if (sortDirection == "Ascending"){data_sorted = (from n in dataorderby GetDynamicSortProperty(n, sortExpression) ascendingselect n).ToList();}else if (sortDirection == "Descending"){data_sorted = (from n in dataorderby GetDynamicSortProperty(n, sortExpression) descendingselect n).ToList();
}
return data_sorted;
}
public object GetDynamicSortProperty(object item, string propName){//Use reflection to get order typereturn item.GetType().GetProperty(propName).GetValue(item, null);}
public object GetDynamicSortProperty(object item, string propName){try{string[] prop = propName.Split('.');
//Use reflection to get order typeint i = 0;while (i < prop.Count()){item = item.GetType().GetProperty(prop[i]).GetValue(item, null);i++;}
return item;}catch (Exception ex){throw ex;}
}
public class Order : IComparable<Order> {
public int CompareTo( Order that ) {if ( that == null ) return 1;if ( this.OrderDate > that.OrderDate) return 1;if ( this.OrderDate < that.OrderDate) return -1;return 0;}}
// in the client code// assume myOrders is a populated List<Order>myOrders.Sort();
public List<Order> GetOrderList<T>(IEnumerable<Order> orders, Func<Order, T> propertySelector){return (from order in ordersorderby propertySelector(order)select order).ToList();}
然后像这样使用它:
var ordersOrderedByDate = GetOrderList(orders, x => x.OrderDate);
您可以更通用,并为您想要订购的内容定义一个开放类型:
public List<T> OrderBy<T,P>(IEnumerable<T> collection, Func<T,P> propertySelector){return (from item in collectionorderby propertySelector(item)select item).ToList();}
并以相同的方式使用它:
var ordersOrderedByDate = OrderBy(orders, x => x.OrderDate);
public class OrderingAscending : IComparer<String>{public int Compare(String x, String y){Int32.TryParse(x, out var xtmp);Int32.TryParse(y, out var ytmp);
int comparedItem = xtmp.CompareTo(ytmp);return comparedItem;}}
你可以在下面的代码中使用它:
IComparer<String> comparerHandle = new OrderingAscending();yourList.Sort(comparerHandle);