为什么一些元组列表是排序而不是其他?

时间:2016-02-11 16:17:35

标签: c# linq icomparer

我需要排序28元组。字符在A-Z,'+','*'。

ASCII顺序是:*,+,A ... Z我希望得到这个顺序:A ... Z,+,*。

为此,我使用此Comparer:

public class AlphabeticPaginationComparer : IComparer<Tuple<char, int>>
{
    public int Compare(Tuple<char, int> a, Tuple<char, int> b)
    {
        // '*' is greater than all letters and '+',
        if (a.Item1 == '*')
        {
            return 1;
        }

        if (b.Item1 == '*')
        {
            return -1;
        }

        // '+' is greater than all letters
        if (a.Item1 == '+')
        {
            return 1;
        }

        if (b.Item1 == '+')
        {
            return -1;
        }

        // Finally we compare letters normally
        return a.Item1 - b.Item1;
    }
}

这是我的代码:

IOrderedEnumerable<Tuple<char, int>> orderedList = 
    origList.OrderBy(c => c, new AlphabeticPaginationComparer());

List<Tuple<char, int>> orderedList2 = orderedList.ToList();

此列表已排序

List<Tuple<char, int>> origList = new List<Tuple<char, int>>
{
    Tuple.Create('L', 15),
    Tuple.Create('R', 12),
    Tuple.Create('E', 3),
    Tuple.Create('P', 9),
    Tuple.Create('B', 30),
    Tuple.Create('C', 13),
    Tuple.Create('M', 11),
    Tuple.Create('A', 5),
    Tuple.Create('V', 5),
    Tuple.Create('H', 6),
    Tuple.Create('S', 5),
    Tuple.Create('G', 15),
    Tuple.Create('T', 8),
    Tuple.Create('D', 15),
    Tuple.Create('K', 4),
    Tuple.Create('I', 2),
    Tuple.Create('F', 7),
    Tuple.Create('W', 3),
    Tuple.Create('+', 6),
    Tuple.Create('O', 1),
    Tuple.Create('Z', 1),
    Tuple.Create('J', 0),
    Tuple.Create('N', 0),
    Tuple.Create('Q', 0),
    Tuple.Create('U', 0),
    Tuple.Create('X', 0),
    Tuple.Create('Y', 0),
    Tuple.Create('*', 176)
};

但不是这个,程序挂起.ToList()。

List<Tuple<char, int>> origList = new List<Tuple<char, int>>
{
    Tuple.Create('A', 70),
    Tuple.Create('C', 119),
    Tuple.Create('B', 27),
    Tuple.Create('G', 39),
    Tuple.Create('D', 22),
    Tuple.Create('E', 21),
    Tuple.Create('F', 20),
    Tuple.Create('I', 25),
    Tuple.Create('H', 14),
    Tuple.Create('J', 4),
    Tuple.Create('K', 9),
    Tuple.Create('L', 24),
    Tuple.Create('M', 50),
    Tuple.Create('N', 5),
    Tuple.Create('O', 15),
    Tuple.Create('P', 17),
    Tuple.Create('R', 12),
    Tuple.Create('S', 68),
    Tuple.Create('T', 18),
    Tuple.Create('U', 12),
    Tuple.Create('V', 19),
    Tuple.Create('W', 5),
    Tuple.Create('X', 1),
    Tuple.Create('Y', 1),
    Tuple.Create('+', 1),
    Tuple.Create('Q', 0),
    Tuple.Create('Z', 0),
    Tuple.Create('*', 618)
};

我尝试使用随机列表,这个问题似乎也是随机的。

欢迎任何帮助。

1 个答案:

答案 0 :(得分:1)

a.Item1 +b.Item1也是+时会发生什么?你需要返回0,而不是1,因为它们是相等的。

以下是解决此问题的方法:

public class AlphabeticPaginationComparer : IComparer<Tuple<char, int>>
{
    public int Compare(Tuple<char, int> a, Tuple<char, int> b)
    {
        if (a.Item1 == b.Item1)
            return 0;

        //...
    }
}