FastPropertyComparer.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* 作者: 季健国
  2. * 创建时间: 2012/7/19 11:19:35
  3. *
  4. */
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Reflection;
  10. using System.Linq.Expressions;
  11. namespace Ant.Service.Common
  12. {
  13. /// <summary>
  14. /// LINQ比较器
  15. /// </summary>
  16. /// <typeparam name="T"></typeparam>
  17. public class FastPropertyComparer<T> : IEqualityComparer<T>
  18. {
  19. private Func<T, Object> getPropertyValueFunc = null;
  20. /// <summary>
  21. /// 通过propertyName 获取PropertyInfo对象
  22. /// </summary>
  23. /// <param name="propertyName"></param>
  24. public FastPropertyComparer(string propertyName)
  25. {
  26. PropertyInfo _PropertyInfo = typeof(T).GetProperty(propertyName,
  27. BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);
  28. if (_PropertyInfo == null)
  29. {
  30. throw new ArgumentException(string.Format("{0} is not a property of type {1}.",
  31. propertyName, typeof(T)));
  32. }
  33. ParameterExpression expPara = Expression.Parameter(typeof(T), "obj");
  34. MemberExpression me = Expression.Property(expPara, _PropertyInfo);
  35. getPropertyValueFunc = Expression.Lambda<Func<T, object>>(me, expPara).Compile();
  36. }
  37. #region IEqualityComparer<T> Members
  38. public bool Equals(T x, T y)
  39. {
  40. object xValue = getPropertyValueFunc(x);
  41. object yValue = getPropertyValueFunc(y);
  42. if (xValue == null)
  43. return yValue == null;
  44. return xValue.Equals(yValue);
  45. }
  46. public int GetHashCode(T obj)
  47. {
  48. object propertyValue = getPropertyValueFunc(obj);
  49. if (propertyValue == null)
  50. return 0;
  51. else
  52. return propertyValue.GetHashCode();
  53. }
  54. #endregion
  55. }
  56. }