C# .NET IComparer排序错误
我最近遇到了一个非常奇怪的问题。我部署了一个新版本的程序,在内部调用IComparer.Compare()方法时收到此错误:C# .NET IComparer排序错误,c#,.net,sorting,compare,icomparer,C#,.net,Sorting,Compare,Icomparer,我最近遇到了一个非常奇怪的问题。我部署了一个新版本的程序,在内部调用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 y
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.".
奇怪的是,我无法在我的电脑上重现这个问题。在VisualStudio2013(调试或发布版本)中,这种情况不会发生,在安装应用程序时也不会发生。更奇怪的是,它甚至不会发生在生产中的每台计算机上,只有30%左右
我的应用程序以.NETFramework4为目标,平台目标是x86
我的代码中只有一个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; }
}
}
有没有其他人遇到过这个问题并找到了解决方案?我的比较器看起来像吗?它覆盖了所有的箱子?我完全不知道这个问题,不知道下一步该怎么办。任何帮助都将不胜感激。
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 ((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;
}
作为旁注,您编写此比较器函数的方式非常低效。您可以加入跟踪以查看值是什么吗?失败?可能是dup:这对你的问题没有直接的帮助,但是看看。那么你就不需要检查,比如说,
l
和l
。谢谢!我最终自己解决了这个问题,碰巧我就是这样解决的。