Skip to content

Instantly share code, notes, and snippets.

@gmcelhanon
Last active December 13, 2017 04:17
Show Gist options
  • Save gmcelhanon/9297fb6c8af1b9efd694669c8d23d78d to your computer and use it in GitHub Desktop.
Save gmcelhanon/9297fb6c8af1b9efd694669c8d23d78d to your computer and use it in GitHub Desktop.
A generically typed equality comparer implementation based on Lambda expressions (removing the need for an explicit class implementation)
using System;
using System.Collections.Generic;
namespace Comparers
{
/// <summary>
/// Implements an equality comparer that allows the method implementations
/// to be supplied as functions in the constructor, eliminating the need
/// for a custom class to be implemented.
/// </summary>
/// <typeparam name="T">The <see cref="Type"/> to be compared.</typeparam>
public class LambdaEqualityComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> _equals;
private readonly Func<T, int> _getHashCode;
/// <summary>
/// Initializes a new instance of the <see cref="LambdaEqualityComparer{T}" /> class using the specified
/// functional equivalents for the methods defined by <see cref="IEqualityComparer{T}"/>.
/// </summary>
/// <param name="equals">The Equals method implementation.</param>
/// <param name="getHashCode">The GetHashCode method implementation.</param>
public LambdaEqualityComparer(Func<T, T, bool> @equals, Func<T, int> getHashCode = null)
{
_equals = @equals;
_getHashCode = getHashCode;
}
/// <summary>Determines whether the specified objects are equal.</summary>
/// <param name="x">The first object to compare.</param>
/// <param name="y">The second object to compare.</param>
/// <returns>true if the specified objects are equal; otherwise, false.</returns>
public bool Equals(T x, T y)
{
return _equals(x, y);
}
/// <summary>Returns a hash code for the specified object.</summary>
/// <param name="obj">The <see cref="T:System.Object" /> for which a hash code is to be returned.</param>
/// <returns>A hash code for the specified object.</returns>
/// <exception cref="T:System.ArgumentNullException">The type of <paramref name="obj" /> is a reference type and <paramref name="obj" /> is null.</exception>
public int GetHashCode(T obj)
{
if (_getHashCode != null)
return _getHashCode(obj);
return obj.GetHashCode();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment