using System;
using System.Collections.Generic;
namespace Umbraco.Core
{
///
/// A custom equality comparer that excepts a delegate to do the comparison operation
///
///
public class DelegateEqualityComparer : IEqualityComparer
{
private readonly Func _equals;
private readonly Func _getHashcode;
#region Implementation of IEqualityComparer
public DelegateEqualityComparer(Func equals, Func getHashcode)
{
_getHashcode = getHashcode;
_equals = equals;
}
public static DelegateEqualityComparer CompareMember(Func memberExpression) where TMember : IEquatable
{
return new DelegateEqualityComparer(
(x, y) => memberExpression.Invoke(x).Equals((TMember)memberExpression.Invoke(y)),
x =>
{
var invoked = memberExpression.Invoke(x);
return !ReferenceEquals(invoked, default(TMember)) ? invoked.GetHashCode() : 0;
});
}
///
/// Determines whether the specified objects are equal.
///
///
/// true if the specified objects are equal; otherwise, false.
///
/// The first object of type to compare.The second object of type to compare.
public bool Equals(T x, T y)
{
return _equals.Invoke(x, y);
}
///
/// Returns a hash code for the specified object.
///
///
/// A hash code for the specified object.
///
/// The for which a hash code is to be returned.The type of is a reference type and is null.
public int GetHashCode(T obj)
{
return _getHashcode.Invoke(obj);
}
#endregion
}
}