对实现许多IEqualityComparers有点懒,并且鉴于我无法轻松地编辑要比较的对象的类实现,因此我选择了以下代码,这些代码与Distinct()和Except()扩展方法一起使用。 :
public class GenericEqualityComparer<T> : IEqualityComparer<T>
{
Func<T, T, bool> compareFunction;
Func<T, int> hashFunction;
public GenericEqualityComparer(Func<T, T, bool> compareFunction, Func<T, int> hashFunction)
{
this.compareFunction = compareFunction;
this.hashFunction = hashFunction;
}
public bool Equals(T x, T y)
{
return compareFunction(x, y);
}
public int GetHashCode(T obj)
{
return hashFunction(obj);
}
}
似乎不错,但每次确实需要提供哈希函数吗?我了解哈希码用于将对象放入存储桶中。不同的存储桶,对象不相等,并且不调用相等。
如果GetHashCode返回相同的值,则调用equals。 (来自:Why is it important to override GetHashCode when Equals method is overridden?)
因此,如果发生错误,例如(并且我听到很多程序员惊恐地尖叫),GetHashCode返回一个常量,以强制将其调用为Equal,则可能会出错?
不会出错,但是在基于哈希表的容器中,进行查找时,您的性能从大约O(1)到O(n)。您最好将所有内容存储在列表中,然后用蛮力搜索满足条件的项目。
如果一个通用用例根据对象的属性之一比较对象,则可以添加一个附加的构造函数并实现并按如下方式调用它:
public GenericEqualityComparer(Func<T, object> projection)
{
compareFunction = (t1, t2) => projection(t1).Equals(projection(t2));
hashFunction = t => projection(t).GetHashCode();
}
var comaparer = new GenericEqualityComparer( o => o.PropertyToCompare);
这将自动使用由属性实现的哈希。
编辑:更有效,更强大的实现激发了我马克的评论:
public static GenericEqualityComparer<T> Create<TValue>(Func<T, TValue> projection)
{
return new GenericEqualityComparer<T>(
(t1, t2) => EqualityComparer<TValue>.Default.Equals( projection(t1), projection(t2)),
t => EqualityComparer<TValue>.Default.GetHashCode(projection(t)));
}
var comparer = GenericEqualityComparer<YourObjectType>.Create( o => o.PropertyToCompare);
您的演奏会费劲。 Distinct
和Except
是在集合数据结构上实现的高效操作。通过提供一个恒定的哈希值,您实际上可以使用线性搜索来破坏此特性并强制采用朴素算法。
您需要查看您的数据量是否可接受。但是对于更大的数据集,差异将是明显的。例如,Except
将从预期时间O(n)增加到O(n²),这可能是一个大问题。
而不是提供常量,为什么不只调用对象自己的GetHashCode
方法?它可能不会给出特别好的值,但它不会比使用常量差,并且除非将对象的GetHashCode
方法重写以返回错误的值,否则仍将保留正确性。
在CodeProject上找到了这个-A Generic IEqualityComparer for Linq Distinct()做得很好。
用例:
IEqualityComparer<Contact> c = new PropertyComparer<Contact>("Name");
IEnumerable<Contact> distinctEmails = collection.Distinct(c);
通用IEqualityComparer
public class PropertyComparer<T> : IEqualityComparer<T>
{
private PropertyInfo _PropertyInfo;
/// <summary>
/// Creates a new instance of PropertyComparer.
/// </summary>
/// <param name="propertyName">The name of the property on type T
/// to perform the comparison on.</param>
public PropertyComparer(string propertyName)
{
//store a reference to the property info object for use during the comparison
_PropertyInfo = typeof(T).GetProperty(propertyName,
BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);
if (_PropertyInfo == null)
{
throw new ArgumentException(string.Format("{0}
is not a property of type {1}.", propertyName, typeof(T)));
}
}
#region IEqualityComparer<T> Members
public bool Equals(T x, T y)
{
//get the current value of the comparison property of x and of y
object xValue = _PropertyInfo.GetValue(x, null);
object yValue = _PropertyInfo.GetValue(y, null);
//if the xValue is null then we consider them equal if and only if yValue is null
if (xValue == null)
return yValue == null;
//use the default comparer for whatever type the comparison property is.
return xValue.Equals(yValue);
}
public int GetHashCode(T obj)
{
//get the value of the comparison property out of obj
object propertyValue = _PropertyInfo.GetValue(obj, null);
if (propertyValue == null)
return 0;
else
return propertyValue.GetHashCode();
}
#endregion
}
我需要将Henrik解决方案重写为实现IEqualityComparer
的类,从而提供了这一点:
public class GenericEqualityComparer<T,TKey> : IEqualityComparer<T>
{
private readonly Func<T, TKey> _keyFunction;
public GenericEqualityComparer(Func<T, TKey> keyFunction)
{
_keyFunction = keyFunction;
}
public bool Equals(T x, T y) => EqualityComparer<TKey>.Default.Equals(_keyFunction(x), _keyFunction(y));
public int GetHashCode(T obj)=> EqualityComparer<TKey>.Default.GetHashCode(_keyFunction(obj));
}
尝试此代码:
public class GenericCompare<T> : IEqualityComparer<T> where T : class
{
private Func<T, object> _expr { get; set; }
public GenericCompare(Func<T, object> expr)
{
this._expr = expr;
}
public bool Equals(T x, T y)
{
var first = _expr.Invoke(x);
var sec = _expr.Invoke(y);
if (first != null && first.Equals(sec))
return true;
else
return false;
}
public int GetHashCode(T obj)
{
return obj.GetHashCode();
}
}
示例:collection = collection.Except(ExistedDataEles,new GenericCompare(x => x.Id))。ToList();