重写 IComparer 以使用 lambda 表达式

Rewriting an IComparer to use a lambda expression

我正在尝试重写我的 IComparer<Animal> 以使用 lambda 表达式,但我似乎无法正确完成此操作

public class AnimalCarriageSorter : IComparer<Animal>
{
    public int Compare(Animal animal, Animal targetAnimal)
    {
        //Compare diet first.
        if (animal.FoodDiet.CompareTo(targetAnimal.FoodDiet) != 0) 
        {
            return animal.FoodDiet.CompareTo(targetAnimal.FoodDiet);
        }

        //Compare size.
        return targetAnimal.Size.CompareTo(animal.Size);
    }
}

问题是您已将比较从 animal.CompareTo(targetAnimal) 切换到 targetAnimal.CompareTo(animal),因此您不会得到一致的结果。在这两种情况下,您都应该将 animal 作为第一个对象。

例如:

public int Compare(Animal animal, Animal targetAnimal)
{
    // Compare diet first.
    if (animal.FoodDiet.CompareTo(targetAnimal.FoodDiet) != 0)
    {
        return animal.FoodDiet.CompareTo(targetAnimal.FoodDiet);
    }

    // Compare size.
    return animal.Size.CompareTo(targetAnimal.Size);
}

或者你可以稍微简化一下:

public int Compare(Animal animal, Animal targetAnimal)
{
    return animal.FoodDiet.CompareTo(targetAnimal.FoodDiet) != 0 
        ? animal.FoodDiet.CompareTo(targetAnimal.FoodDiet) 
        : animal.Size.CompareTo(targetAnimal.Size);
}

您可以使用 Func<Animal, Animal, int> 而不是 IComparer<Animal> 轻松重写它,例如

Func<Animal, Animal, int> comparer = (x, y) => 
    x.FoodDiet.CompareTo(y.FoodDiet) != 0 ? 
        x.FoodDiet.CompareTo(y.FoodDiet) : 
        x.Size.CompareTo(y.Size)