Linq 查询中的运算符重载
运算符重载在 C# 代码中工作得非常完美,因为我正在尝试以下方式。
**
public class HostCode
{
public string Code { get; set; }
public string Name { get; set; }
public static bool operator ==(HostCode hc1, HostCode hc2)
{
return hc1.Code == hc2.Code;
}
public static bool operator !=(HostCode hc1, HostCode hc2)
{
return true;
}
}**
我有一个名为 HostCode 的类,它包含 2 个重载方法(一个用于 '==',另一个用于 '!=') 我在下面创建了一组主机代码。
**var hostCodes = new List<HostCode>()
{
new HostCode(){ Code = "1", Name = "sreekanth" },
new HostCode(){ Code = "2", Name = "sajan" },
new HostCode(){ Code = "3", Name = "mathew" },
new HostCode(){ Code = "4", Name = "sachin" }
};**
***var hc = new HostCode() { Code = "1", Name = "sreekanth" };***
***var isEq = hostCodes[1] == hc;***
当我像上面一样尝试时,相应的运算符方法在 HostCode 类中触发(在本例中为“==”)。这样我就可以在那里编写我的自定义逻辑。
但是,如果我尝试使用如下的 Linq 查询,它不会触发。但在这种情况下,我还比较具有相同类型的两个对象。
**var isEqual = from obj in hostCodes where (HostCode)obj == (HostCode)hc select obj;**
谁能帮我找到一种通过 Linq 查询比较 2 个对象的方法?
Operator overloading is working perfect in C# code, since I am trying in the following way.
**
public class HostCode
{
public string Code { get; set; }
public string Name { get; set; }
public static bool operator ==(HostCode hc1, HostCode hc2)
{
return hc1.Code == hc2.Code;
}
public static bool operator !=(HostCode hc1, HostCode hc2)
{
return true;
}
}**
I have a clas called HostCode and it contains 2 overloading methods (one for '==' and another for '!=')
And I created a collection of Host Codes below.
**var hostCodes = new List<HostCode>()
{
new HostCode(){ Code = "1", Name = "sreekanth" },
new HostCode(){ Code = "2", Name = "sajan" },
new HostCode(){ Code = "3", Name = "mathew" },
new HostCode(){ Code = "4", Name = "sachin" }
};**
***var hc = new HostCode() { Code = "1", Name = "sreekanth" };***
***var isEq = hostCodes[1] == hc;***
when I am trying like above, the respective operator method fired in HostCode class (in this case it is '=='). So that I can write my custom logic there.
But if Iam trying with a Linq query as below, it is not firing. But in this case also Iam comparing 2 objects having same type.
**var isEqual = from obj in hostCodes where (HostCode)obj == (HostCode)hc select obj;**
Can anyone please help me to find out a way which I can compare 2 objects by Linq queries?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 IEqualityComparer 或覆盖 等于 用于此目的。
IEqualityComparer 的用法是当您在对象上有一些相等性并且在某些函数(例如 Contain)中,...您想要使用一些特定的相等性时:
You can use IEqualityComparer or override equals for this purpose.
And IEqualityComparer usage is when you have some equality on object and in some functions like Contain, ... you want use some specific equality:
既然你的问题是“我应该如何比较它们才能工作”,我会回答“你应该重载并使用
.Equals()
而不是==
”您的
!=
重载定义?Since your question is "how should I compare them for this to work" I would answer "you should overload and use
.Equals()
instead of==
"And what's with your overload definition of
!=
?