c# List排序

list.Sort((s1, s2)=> s1.CompareTo(s2));

5.CompareTo(6) = -1 First int is smaller. 6.CompareTo(5) = 1 First int is larger. 5.CompareTo(5) = 0 Ints are equal.


orderList.Sort(delegate(Order p1,Order p2){int compareDate = p1.Date.CompareTo(p2.Date);if(compareDate ==0){return p2.OrderID.CompareTo(p1.OrderID);}return compareDate;});


his would give you ascending dates with descending orderIds. However, I wouldn't recommend sticking delegates as it will mean lots of places without code re-use. You should implement an IComparer and just pass that through to your Sort method. See here. 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; } } And then to use this IComparer class, just instantiate it and pass it to your Sort method: IComparer<Order> comparer = new MyOrderingClass(); orderList.Sort(comparer);

你可能感兴趣的:(list排序)