我正在使用LINQ .Find(),当它找到匹配时它不会停止.我有:
List<ipFound> ipList = new List<ipFound>();
ipFound ipTemp = ipList.Find(x => x.ipAddress == srcIP);
if (ipTemp == null) {
// this is always null
}
public class ipFound
{
public System.Net.IPAddress ipAddress;
public int bytesSent;
public int bytesReceived;
public int bytesTotal;
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?我在这里疯了.
谢谢!
Jon*_*n B 13
你需要使用.Equals而不是==.
var a = IPAddress.Parse("1.2.3.4");
var b = IPAddress.Parse("1.2.3.4");
Console.WriteLine(a == b); // False
Console.WriteLine(a.Equals(b)); // True
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,a == b是False因为它们是两个不同的对象.然而,a.Equals(b)是True因为它们具有相同的值.
And*_*ker 11
使用IPAddress.Equals而不是比较references(==):
ipFound ipTemp = ipList.Find(x => x.ipAddress.Equals(srcIP));
Run Code Online (Sandbox Code Playgroud)
作为旁注,通常类名是PascalCased(IPFoundvs. ipFound)
示例: http ://ideone.com/lAeiMm