CodePaste Logo
New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

PredicateEqualityComparer<T>

258 Views
Copy Code Show/Hide Line Numbers
   1:  [Serializable]
   2:  public class PredicateEqualityComparer<T> : EqualityComparer<T>
   3:  {
   4:      private Func<T, T, bool> predicate;
   5:   
   6:      public PredicateEqualityComparer(Func<T, T, bool> predicate)
   7:          : base()
   8:      {
   9:          this.predicate = predicate;
  10:      }
  11:   
  12:      public override bool Equals(T x, T y)
  13:      {
  14:          return (x == null)
  15:              ? (y == null)
  16:              : ((y != null) && this.predicate(x, y));
  17:      }
  18:   
  19:      [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  20:      public override int GetHashCode(T obj)
  21:      {
  22:          // Always return the same value to force the call to IEqualityComparer<T>.Equals
  23:          return 0;
  24:      }
  25:   
  26:      public override bool Equals(object obj)
  27:      {
  28:          PredicateEqualityComparer<T> comparer = obj as PredicateEqualityComparer<T>;
  29:          return (comparer != null);
  30:      }
  31:   
  32:      public override int GetHashCode()
  33:      {
  34:          return base.GetType().Name.GetHashCode();
  35:      }
  36:  }
by Paulo Morgado
  April 10, 2010 @ 5:12am
Tags:
Description:
Generic equality comparer that takes a predicate as the comaparison method.

Add a comment


Report Abuse
brought to you by:
West Wind Techologies



If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate