運算符重載在C#代碼中運行良好,因爲我嘗試的方式如下。運算符在Linq查詢中重載
**
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;
}
}**
我有一個名爲CLAS和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類中觸發相應的運算符方法(在本例中爲'==')。所以我可以在那裏寫我的自定義邏輯。
但是,如果IAM嘗試與下面的Linq查詢,它不會觸發。但在這種情況下,Iam也會比較兩個具有相同類型的對象。
**var isEqual = from obj in hostCodes where (HostCode)obj == (HostCode)hc select obj;**
任何人都可以請幫助我找出一種方法,我可以通過Linq查詢比較2個對象嗎?
去這裏的答案 - HTTP:/ /stackoverflow.com – jjnguy
hc從哪裏來 – msarchet