Generic IEqualityComparer and GetHashCode

后端 未结 6 1550
-上瘾入骨i
-上瘾入骨i 2020-12-31 11:01

Being somewhat lazy about implementing lots of IEqualityComparers, and given that I couldn\'t easily edit class implementations of object being compared, I went with the fol

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-31 11:54

    If a common use-case is comparing objects according to one of their properties, you could add an additional constructor and implement and call it like this:

    public GenericEqualityComparer(Func projection)
    {
        compareFunction = (t1, t2) => projection(t1).Equals(projection(t2));
        hashFunction = t => projection(t).GetHashCode();
    }
    
    var comaparer = new GenericEqualityComparer( o => o.PropertyToCompare);
    

    This will automatically use the hash as implemented by the property.

    EDIT: a more efficient and robust implementation inspired my Marc's comments:

    public static GenericEqualityComparer Create(Func projection)
    {
        return new GenericEqualityComparer(
            (t1, t2) => EqualityComparer.Default.Equals( projection(t1), projection(t2)),
            t => EqualityComparer.Default.GetHashCode(projection(t)));
    }
    
    var comparer = GenericEqualityComparer.Create( o => o.PropertyToCompare); 
    

提交回复
热议问题