重写IComparer以使用Lambda表达式

时间:2019-04-09 19:29:51

标签: c# lambda icomparable

我正在尝试重写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);
    }
}

2 个答案:

答案 0 :(得分:3)

例如,您可以轻松地使用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)

答案 1 :(得分:1)

问题是您已将比较从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);
}