How do C # Linq extension methods perform equality comparison?

So, the following lambda expression does not return any elements in the collection, although during the transition I was able to check whether 1 element meets the criteria. I added a class sample with its IEquatable implementation.

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

The above returns nothing. Any suggestions on what to do to make the above expression?

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);
    }
}

To make sure I'm not crazy, I created the following nUnit test, which passes:

    [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);
    }

Trying to override == and! =:

    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);
    }
+3
source share
4 answers

They are used EqualityComparer<T>.Defaultfor equality comparisons and Comparer<T>.Defaultfor ordered comparisons.

MSDN - EqualityComparer<T>.Default :

Default , T System.IEquatable(Of T), EqualityComparer(Of T), . EqualityComparer(Of T), Object.Equals Object.GetHashCode, T.

MSDN - Comparer<T>.Default :

Comparer(Of T), , System.IComparable(Of T) (IComparable<T> #, IComparable(Of T) Visual Basic) . T System.IComparable(Of T), Comparer(Of T), System.IComparable.

+5

==.

:

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

IdentityKey ( Guid) - == operator.

, , "" , ==. .. if(guidValue = identityKeyValue) if((IdentityKey)guidValue == identityKeyValue)

.Equals , ?

0

Source: https://habr.com/ru/post/1734470/


All Articles