Generic IEqualityComparer and GetHashCode

后端 未结 6 1537
-上瘾入骨i
-上瘾入骨i 2020-12-31 11:01

Being somewhat lazy about implementing lots of IEqualityComparers, and given that I couldn\'t easily edit class implementations of object being compared, I went with the fol

6条回答
  •  清酒与你
    2020-12-31 11:50

    Found this one on CodeProject - A Generic IEqualityComparer for Linq Distinct() nicely done.

    Use case:

    IEqualityComparer c =  new PropertyComparer("Name");
    IEnumerable distinctEmails = collection.Distinct(c); 
    

    Generic IEqualityComparer

    public class PropertyComparer : IEqualityComparer
    {
        private PropertyInfo _PropertyInfo;
    
        /// 
        /// Creates a new instance of PropertyComparer.
        /// 
        /// The name of the property on type T 
        /// to perform the comparison on.
        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 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
    }  
    

提交回复
热议问题