为什么某些元组列表是排序的,而不是其他的
本文关键字:其他 排序 元组 列表 为什么 | 更新日期: 2023-09-27 18:34:17
我需要对 28 个元组进行排序。字符以 A-Z、"+"、"*"表示。
ASCII 顺序为: *, +, A...Z 和我想得到这个订单:A...Z, +, *.
为此,我使用此比较器:
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)
};
我尝试使用随机列表,这个问题似乎也是随机的。
欢迎任何帮助。
当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;
//...
}
}