我正在尝试找到一种优雅的方法来使用 LINQ 对整数序列进行词法排序。换句话说,如果我有这些整数序列
- 7、10、12、14、15
- 10、12、15
- 10
- 7, 15
- 14、15
我希望它们能像这样排序
- 7、10、12、14、15
- 7, 15
- 10
- 10、12、15
- 14、15
这与按字符对字符串进行排序的基本思想相同,只是我想对整数序列进行排序。我不想按字母顺序排序,但我确实希望序列按词法排序。
最佳答案
您想要的排序类型称为 lexical sort :
Given two partially ordered sets A and B, the lexicographical order on the Cartesian product A × B is defined as (a,b) ≤ (a′,b′) if and only if a < a′ or (a = a′ and b ≤ b′).
.Net 为您提供了在排序时指定所需比较类型的工具。有两个结构可以控制它: IComparer
和 Comparison<T>
代表。您可以将其中之一传递给 List.Sort
。示例:
var lists = new List<Int32[]> {
new [] { 7, 10, 12, 14, 15 },
new [] { 7, 15 },
new [] { 7, 15 },
new [] { 10 },
new [] { 10, 12, 15 },
new [] { 14, 15 } };
lists.Sort((a, b) => {
var result = a.Zip(b, Tuple.Create)
.Select(t => t.Item1.CompareTo(t.Item2))
.FirstOrDefault(c => c != 0);
return result == 0 && !a.Any() ? -1 : result; // Empty list minimum
});
这通过了Comparison<Int32[]>
代表zips比较数,允许逐个元素比较,并在检测到第一个非零整数比较时停止比较。如果没有找到不相等的元素,则返回 Int32
的默认值。为 0,表示列表按字典顺序相等。
(请注意,我向您的列表集中添加了另一个元素,以显示相等的整数列表排序正确。)
奖励闲聊:
我认为这种方法比分配字符串和使用 OrderBy
更快但经过分析后,速度没有明显差异。我尝试使用 struct
使其更快而不是Tuple
,这确实有一点帮助,并且可能节省了 GC 分配和内存使用,但我没有测量内存使用性能。如果性能是一个问题,您可能最终会避开整洁的 Linq 方法并编写 Comparer
使用循环。
关于linq - 使用 LINQ 按字典顺序对整数序列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33028197/