我有以下简单的 LINQ to Object 查询:
var accountsWithOpportunities = (from a in accountGetServices
join o in opportunities on a equals o.Account
select a).ToList();
此查询始终为 0 个结果,但此查询不是:
var accountsWithOpportunities = (from a in accountGetServices
join o in opportunities on a.Id equals o.Account.Id
select a).ToList();
因此,我得出结论,我的平等操作做错了。 我有以下用于所有模型的抽象类:
public abstract class BaseModel<T> : BaseModel
where T : class, IIdentifyable
{
public static bool operator ==(BaseModel<T> c1, BaseModel<T> c2)
{
T t1 = c1 as T;
T t2 = c2 as T;
if (object.ReferenceEquals(t1, t2)) return true;
if (object.ReferenceEquals(t1, null)) return false;
if (object.ReferenceEquals(t2, null)) return false;
return c1.Equals(c2);
}
public static bool operator !=(BaseModel<T> c1, BaseModel<T> c2)
{
return !(c1 == c2);
}
}
public abstract class BaseModel : IEquatable<BaseModel>
{
public bool Equals(BaseModel other)
{
if (other == null)
return false;
var identifyable1 = this as IIdentifyable;
var identifyable2 = other as IIdentifyable;
return identifyable1.Id == identifyable2.Id;
}
public override bool Equals(object obj)
{
return base.Equals(obj) && Equals(obj as BaseModel);
}
}
我在每个函数上放置了断点以查看引擎盖下发生了什么,但没有一个被击中。
我做错了什么?
最佳答案
public override bool Equals(object obj)
{
return base.Equals(obj) && Equals(obj as BaseModel);
}
这部分好像是错的。 base.Equals
调用 object.ReferenceEquals
,它总是(或至少在大多数情况下)返回 false,因此永远不会计算另一个表达式。
编辑
此外,正如您之前指出的那样,调用了 GetHashCode(您应该收到编译器警告,提示您已覆盖 Equals 而不是 GetHashCode)。因此,更改 GetHashCode 以返回实体的 Id,它应该开始工作了。
关于c# - LINQ to Object Join 运算符和相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8081171/