【问题标题】:.NET IComparer sort error.NET IComparer 排序错误
【发布时间】:2015-09-15 19:03:13
【问题描述】:

我最近遇到了一个非常奇怪的问题。我部署了一个新版本的程序,并在内部调用 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.".

奇怪的是,我无法在我的计算机上重现此问题。我在 Visual Studio 2013(调试或发布版本)中不会发生这种情况,安装应用程序时也不会发生这种情况。更奇怪的是,它甚至不会发生在生产中的每台计算机上,只有大约 30%。

我的应用程序面向 .NET Framework 4,平台目标是 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; }
    }
}

有没有其他人遇到过这个问题并找到了解决方案?我的比较器看起来是否涵盖了所有情况?我完全迷失了这个问题,不知道下一步该尝试什么。任何帮助将不胜感激。

【问题讨论】:

标签: c# .net sorting compare icomparer


【解决方案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;
    }

顺便说一句,您编写此比较器函数的方式非常低效。

【讨论】:

  • 谢谢!我最终自己解决了这个问题,而这正是我修复它的方式。
猜你喜欢
  • 1970-01-01
  • 2010-09-17
  • 1970-01-01
  • 2012-12-29
  • 1970-01-01
  • 1970-01-01
  • 2012-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多