首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >.NET IComparer排序错误

.NET IComparer排序错误
EN

Stack Overflow用户
提问于 2015-09-15 19:03:13
回答 1查看 1.5K关注 0票数 1

我最近遇到了一个很奇怪的问题。我部署了一个新版本的程序,并在内部调用IComparer.Compare()方法时收到此错误:

代码语言:javascript
复制
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 2013 (调试或发布版本)中不会发生这种情况,在安装应用程序时也不会发生这种情况。让事情变得更奇怪的是,它甚至不会发生在生产中的每台电脑上,只有大约30%。

我的应用程序目标是.NET框架4,平台目标是x86。

在我的代码中只有一个IComparer对象的实例,如下所示:

代码语言:javascript
复制
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; }
    }
}

有没有其他人有过这个问题,并找到了解决办法?我的比较者看它涵盖了所有的情况吗?我对这个问题完全不知所措,不知道下一步该做什么。任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-15 19:18:56

代码语言:javascript
复制
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;
    }

应该是

代码语言:javascript
复制
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;
    }

顺便提一句,你写这个比较函数的方式是非常无效的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32593666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档