How to create a simple 'EqualityComparer<T>' using a lamba expression - Online Free Computer Tutorials.

'Software Development, Games Development, Mobile Development, iOS Development, Android Development, Window Phone Development. Dot Net, Window Services,WCF Services, Web Services, MVC, MySQL, SQL Server and Oracle Tutorials, Articles and their Resources

Monday, February 15, 2016

How to create a simple 'EqualityComparer' using a lamba expression

What about a throw away IEqualityComparer generic class ?

public class ThrowAwayEqualityComparer<T> : IEqualityComparer<T>  {    Func<T, T, bool> comparer;      public ThrowAwayEqualityComparer<T>(Func<T, T, bool> comparer)    {      this.comparer = comparer;    }      public bool Equals(T a, T b)    {      return comparer(a, b);    }      public int GetHashCode(T a)    {      return a.GetHashCode();    }  }
So now you can use Distinct.

var distinctImages = allImages.Distinct(     new ThrowAwayEqualityComparer<GalleryImage>((a, b) => a.Key == b.Key));
You might be able to get away with the <GalleryImage>, but I'm not sure if the compiler could infer the type (don't have access to it right now.)

And in an additional extension method:

public static class IEnumerableExtensions  {    public static IEnumerable<TValue> Distinct<TValue>(this IEnumerable<TValue> @this, Func<TValue, TValue, bool> comparer)    {      return @this.Distinct(new ThrowAwayEqualityComparer<TValue>(comparer);    }      private class ThrowAwayEqualityComparer...  }

I guess you came to this post by searching similar kind of issues in any of the search engine and hope that this resolved your problem. If you find this tips useful, just drop a line below and share the link to others and who knows they might find it useful too. 

Stay tuned to my blogtwitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. We will not share your email address to anybody as we respect privacy.

No comments:

Post a Comment