Comparison 、IComparer

一个是委托,一个是接口,

// Summary:
// Defines a method that a type implements to compare two objects.
//
// Type parameters:
// T:
// The type of objects to compare.This type parameter is contravariant. That
// is, you can use either the type you specified or any type that is less derived.
// For more information about covariance and contravariance, see Covariance
// and Contravariance in Generics.
public interface IComparer<in T>
{
// Summary:
// Compares two objects and returns a value indicating whether one is less than,
// equal to, or greater than the other.
//
// Parameters:
// x:
// The first object to compare.
//
// y:
// The second object to compare.
//
// Returns:
// A signed integer that indicates the relative values of x and y, as shown
// in the following table.Value Meaning Less than zerox is less than y.Zerox
// equals y.Greater than zerox is greater than y.
int Compare(T x, T y);
}

定义如下:如果返回负数,表示x<y,如果返回正数,表示x>y,在排序中可以这么理解,

x<y,返回负数,表示承认x比y小,这样就能排出升序的效果。

deductionStrategyEntitiesTmp.Sort((x, y) =>
{
if (x.StartAmount > y.StartAmount) return -1;
else if (x.StartAmount < y.StartAmount) return 1;
else return 0;
}); //扣减金额递减

  //分数由大变小

Collections.sort(promotionActivitiesResult, new Comparator<PromotionActivity>() {
@Override
public int compare(PromotionActivity o1, PromotionActivity o2) {
return o2.getSortScore() > o1.getSortScore() ? 1 : o2.getSortScore() < o1.getSortScore() ? -1 : 0;
}
});
原文地址:https://www.cnblogs.com/wuMing-dj/p/5416981.html