LoginSignup
4
2

More than 5 years have passed since last update.

IEqualityComparerが面倒という話

Last updated at Posted at 2016-11-28

LINQでまれに使うことのあるIEqualityComparerだが、
いちいちクラスを定義するのが面倒なので、
とりあえず、諸々の責任は放棄したこんなクラスでもあれば、概ねはどうにかなると思う。

GenericEqualityComparer.cs
public class GenericEqualityComparer<T> : IEqualityComparer<T>
{
    private Func<T, T, bool> _predicate;
    private Func<T, int> _gethash;

    public GenericEqualityComparer(Func<T, T, bool> predicate)
        : this(predicate, obj => obj.GetHashCode())
    {
    }
    public GenericEqualityComparer(Func<T, T, bool> predicate, Func<T, int> gethash)
    {
        _predicate = predicate;
        _gethash = gethash;
    }

    public bool Equals(T x, T y)
    {
        return _predicate(x, y);
    }
    public int GetHashCode(T obj)
    {
        return _gethash(obj);
    }
}
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2