Как ожидать некоторых (но не всех) аргументов с RSpec should_receive?

Для любого, кто все еще смотрит; вот еще один способ реализации пользовательского лямбда-компаратора.

public class LambdaComparer<T> : IEqualityComparer<T>
    {
        private readonly Func<T, T, bool> _expression;

        public LambdaComparer(Func<T, T, bool> lambda)
        {
            _expression = lambda;
        }

        public bool Equals(T x, T y)
        {
            return _expression(x, y);
        }

        public int GetHashCode(T obj)
        {
            /*
             If you just return 0 for the hash the Equals comparer will kick in. 
             The underlying evaluation checks the hash and then short circuits the evaluation if it is false.
             Otherwise, it checks the Equals. If you force the hash to be true (by assuming 0 for both objects), 
             you will always fall through to the Equals check which is what we are always going for.
            */
            return 0;
        }
    }

вы можете затем создать расширение для linq Distinct, которое может принимать в lambda's

   public static IEnumerable<T> Distinct<T>(this IEnumerable<T> list,  Func<T, T, bool> lambda)
        {
            return list.Distinct(new LambdaComparer<T>(lambda));
        }  

Использование:

var availableItems = list.Distinct((p, p1) => p.Id== p1.Id);
23
задан B Seven 7 October 2013 в 19:32
поделиться