Linq Distinct方法的参数扩展

来源:互联网 发布:系统盘垃圾清理软件 编辑:程序博客网 时间:2024/05/11 01:05


 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
        public PropertyComparer(string propertyName)
        {
            _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)));
            }
        }
        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();
        }
    }
0 0