So, the following lambda expression is not returning any elements in the collection, even though while stepping through I was able to verify that 1 item matches the criteria. I've added a sample of the class with it's IEquatable implementation.
...within a method, foo is a method parameter
var singleFoo = _barCollection.SingleOrDefault(b => b.Foo == foo);
The above returns nothing. Any suggestions as to what to do to make the expression above work?
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 didn't go insane, 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);
}
Attempt at overriding == 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);
}