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

SelectorEqualityComparer<TSource, Tkey>

300 Views
Copy Code Show/Hide Line Numbers
   1:  [Serializable]
   2:  public class SelectorEqualityComparer<TSource, Tkey> : EqualityComparer<TSource>
   3:  {
   4:      private Func<TSource, Tkey> selector;
   5:   
   6:      public SelectorEqualityComparer(Func<TSource, Tkey> selector)
   7:          : base()
   8:      {
   9:          this.selector = selector;
  10:      }
  11:   
  12:      public override bool Equals(TSource x, TSource y)
  13:      {
  14:          Tkey xKey = this.GetKey(x);
  15:          Tkey yKey = this.GetKey(y);
  16:   
  17:          if (xKey != null)
  18:          {
  19:              return ((yKey != null) && xKey.Equals(yKey));
  20:          }
  21:   
  22:          return (yKey == null);
  23:      }
  24:   
  25:      [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  26:      public override int GetHashCode(TSource obj)
  27:      {
  28:          Tkey key = this.GetKey(obj);
  29:   
  30:          return (key == null) ? 0 : key.GetHashCode();
  31:      }
  32:   
  33:      public override bool Equals(object obj)
  34:      {
  35:          SelectorEqualityComparer<TSource, Tkey> comparer = obj as SelectorEqualityComparer<TSource, Tkey>;
  36:          return (comparer != null);
  37:      }
  38:   
  39:      public override int GetHashCode()
  40:      {
  41:          return base.GetType().Name.GetHashCode();
  42:      }
  43:   
  44:      [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
  45:      private Tkey GetKey(TSource obj)
  46:      {
  47:          return (obj == null) ? (Tkey)(object)null : this.selector(obj);
  48:      }
  49:  }
by Paulo Morgado
  April 10, 2010 @ 5:18am
Tags:
Description:
Generic equality comparer that takes a key selector 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