C#Linq扩展方法如何执行相等比较?

时间:2010-02-25 21:38:00

标签: c# linq extension-methods iequatable

因此,以下lambda表达式不会返回集合中的任何元素,即使在单步执行时我能够验证1个项目是否符合条件。我已经用它的IEquatable实现添加了一个类的样本。

...within a method, foo is a method parameter
var singleFoo = _barCollection.SingleOrDefault(b => b.Foo == foo);

以上都没有回报。关于如何使上述表达式起作用的任何建议?

public class Foo: IEquatable<Foo> 
{
    public string KeyProperty {get;set;}
    public bool Equals(Foo other)
    {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;
        return other.KeyProperty==KeyProperty;
    }
    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != typeof (Foo)) return false;
        return Equals((Foo) obj);
    }
    public override int GetHashCode()
    {
        return (KeyProperty != null ? KeyProperty.GetHashCode() : 0);
    }
}

为了确保我没有疯狂,我创建了以下nUnit测试,该测试通过:

    [Test]
    public void verify_foo_comparison_works()
    {
        var keyString = "keyValue";
        var bar = new Bar();
        bar.Foo = new Foo { KeyProperty = keyString };
        var basicFoo = new Foo { KeyProperty = keyString };
        var fromCollectionFoo = Bars.SingleFooWithKeyValue;
        Assert.AreEqual(bar.Foo,basicFoo);
        Assert.AreEqual(bar.Foo, fromCollectionFoo);
        Assert.AreEqual(basicFoo, fromCollectionFoo);
    }

尝试覆盖==和!=:

    public static bool operator ==(Foo x, Foo y)
    {
        if (ReferenceEquals(x, y))
            return true;
        if ((object)x == null || (object)y == null)
            return false;
        return x.KeyProperty == y.KeyProperty;
    }
    public static bool operator !=(Foo x, Foo y)
    {
        return !(x == y);
    }

4 个答案:

答案 0 :(得分:5)

他们使用EqualityComparer<T>.Default进行相等比较,使用Comparer<T>.Default进行有序比较。

  

MSDN - EqualityComparer<T>.Default备注:

     

Default属性检查类型T是否实现System.IEquatable(Of T)通用接口,如果是,则返回使用该实现的EqualityComparer(Of T)。否则,它会返回使用EqualityComparer(Of T)提供的Object.EqualsObject.GetHashCode覆盖的T

     

MSDN - Comparer<T>.Default备注:

     

此属性返回的Comparer(Of T)使用System.IComparable(Of T)通用接口(C#中的IComparable<T>,Visual Basic中的IComparable(Of T))来比较两个对象。如果类型T未实现System.IComparable(Of T)通用接口,则此属性将返回使用Comparer(Of T)接口的System.IComparable

答案 1 :(得分:4)

您没有重新定义==运算符。

更改为:

var singleFoo = _barCollection.SingleOrDefault(b => b.Foo.Equals(foo));

答案 2 :(得分:0)

您还需要override the == operator

答案 3 :(得分:0)

我遇到了类似问题的IdentityKey类(具有隐式Guid转换) - 在这种情况下,包含== operator覆盖并不可行。

我说这不可行,因为通过“混合”比较,我现在必须转换类型以避免==运算符重载的歧义。 ie。而不是if(guidValue = identityKeyValue),它必须成为if((IdentityKey)guidValue == identityKeyValue)

虽然使用.Equals是一种解决方案,但对我来说这感觉并不自然?