Quantcast
Channel: Jacob Gable's Posterous
Viewing all articles
Browse latest Browse all 17

DelegableEqualityComparer Dirtiness...

$
0
0


Occasionally I like to just get something done with some Lambda expressions that probably should be more properly architected.


In case someone else feels like doing something a little naughty with Lambda expressions, here is an example of what I call a DelegableEqualityComparer that will take as parameters the equality function to use and the function to generate a HashCode.


Disclaimer:  I didn't say it's the right way, just that it might be useful sometime.


   public class DelegableEqualityComparer<T> : IEqualityComparer<T>

   {

       private Func<T, T, bool> equalsFunc;

       private Func<T, int> hashFunc;

 

       public DelegableEqualityComparer(Func<T,T,bool> EqualityFunction, Func<T, int> HashFunction)

       {

           equalsFunc = EqualityFunction;

           hashFunc = HashFunction;

       }

 

       #region IEqualityComparer<T> Members

 

       public bool Equals(T x, T y)

       {

           return equalsFunc.Invoke(x, y);

       }

 

       public int GetHashCode(T obj)

       {

           return hashFunc.Invoke(obj);

       }

 

       #endregion

   }



// Example of inheriting for simple comparers.

   public class ValidationResultMessageComparer :

                DelegableEqualityComparer<ValidationResult>

   {

       public ValidationResultMessageComparer()

           : base(

               // Equality Comparer

               (x, y) => String.Equals(x.Message, y.Message),

               // HashCode

               (o) => o.Message.GetHashCode()

           )

       {

 

       }

   }



// Example of using in-line

foreach ( var result in results.Distinct(new DelegableEqualityComparer<ValidationResult>((x,y) => x.Message.Equals(y.Message), o => o.Message.GetHashCode())))

{

       // Your distinct results...

}


Now Playing: Rick Ross - Hustlin' Remix

Permalink | Leave a comment  »


Viewing all articles
Browse latest Browse all 17

Trending Articles