[英].NET IComparer sort error
I have run into a very weird issue recently. 我最近遇到了一个很奇怪的问题。 I deployed a new version of a program and am receiving this error when the IComparer.Compare() method gets called internally:
我部署了程序的新版本,并在内部调用IComparer.Compare()方法时收到此错误:
Unable to sort because the IComparer.Compare0 method returns inconsistent
results. Either a value does not compare equal to itself, or one value repeatedly
compared to another value yields different results. x:",x's type: 'String',
IComparer.".
The odd thing is that I cannot reproduce this issue on my computer. 奇怪的是,我无法在计算机上重现此问题。 It doesn't happen for me in Visual Studio 2013 (debug or release versions) and it doesn't happen when I install the application either.
在Visual Studio 2013(调试版或发行版)中,这对我而言不会发生,在我安装应用程序时也不会发生。 To make things weirder, it doesn't even happen on every computer in production, only about 30% of them.
使事情变得奇怪的是,它甚至不在生产中的每台计算机上发生,只有其中的30%左右。
My application targets .NET Framework 4 and the platform target is x86. 我的应用程序以.NET Framework 4为目标,平台目标为x86。
There is only one instance of an IComparer object in my code, here it is: 我的代码中只有一个IComparer对象的实例,这里是:
public int Compare(string stringOne, string stringTwo)
{
if (stringOne == stringTwo) { return 0; }
else if (stringOne == null) { return stringTwo == null ? 0 : -1; }
else if (stringTwo == null) { return stringOne == null ? 0 : 1; }
else if (stringOne.StartsWith("_") && !stringTwo.StartsWith("_"))
{
return -1;
}
else if (!stringOne.StartsWith("_") && stringTwo.StartsWith("_"))
{
return 1;
}
else if ((stringOne.StartsWith("l") || stringOne.StartsWith("L")) &&
(!stringTwo.StartsWith("l") || !stringTwo.StartsWith("L")))
{
return -1;
}
else if ((!stringOne.StartsWith("l") || !stringOne.StartsWith("L")) &&
(stringTwo.StartsWith("l") || stringTwo.StartsWith("L")))
{
return 1;
}
else
{
if (stringTwo == null) { return 1; }
else { return stringOne.CompareTo(stringTwo) == 1 ? -1 : 1; }
}
}
Has anyone else had this issue and found a solution to it? 是否还有其他人遇到过此问题并找到了解决方案? Does my comparer look it covers all cases?
我的比较器看起来是否涵盖所有情况? I am totally lost about this issue and have no idea what to try next.
我完全不知道这个问题,也不知道下一步该怎么做。 Any help will be greatly appreciated.
任何帮助将不胜感激。
This 这个
else if ((stringOne.StartsWith("l") || stringOne.StartsWith("L")) &&
(!stringTwo.StartsWith("l") || !stringTwo.StartsWith("L")))
{
return -1;
}
else if ((!stringOne.StartsWith("l") || !stringOne.StartsWith("L")) &&
(stringTwo.StartsWith("l") || stringTwo.StartsWith("L")))
{
return 1;
}
should be 应该
else if ((stringOne.StartsWith("l") || stringOne.StartsWith("L")) &&
!(stringTwo.StartsWith("l") || stringTwo.StartsWith("L")))
{
return -1;
}
else if (!(stringOne.StartsWith("l") || stringOne.StartsWith("L")) &&
(stringTwo.StartsWith("l") || stringTwo.StartsWith("L")))
{
return 1;
}
As a side note, the way you wrote this comparer function is highly ineffecient. 附带说明一下,您编写此比较器函数的方式效率很低。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.