进行字母数字排序

进行字母数字排序

本文介绍了使用 LINQ 进行字母数字排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 string[],其中每个元素都以某个数值结尾.

I have a string[] in which every elements ends with some numeric value.

string[] partNumbers = new string[]
{
    "ABC10", "ABC1","ABC2", "ABC11","ABC10", "AB1", "AB2", "Ab11"
};

我正在尝试使用 LINQ 按如下方式对上述数组进行排序,但没有得到预期的结果.

I am trying to sort the above array as follows using LINQ but I am not getting the expected result.

var result = partNumbers.OrderBy(x => x);

实际结果:

AB1
Ab11
AB2
ABC1
ABC10
ABC10
ABC11
ABC2

预期结果

AB1
AB2
AB11
..

推荐答案

这是因为字符串的默认排序是标准字母数字字典(词典)排序,而 ABC11 将在 ABC2 之前,因为排序总是从左到右进行.

That is because the default ordering for string is standard alpha numeric dictionary (lexicographic) ordering, and ABC11 will come before ABC2 because ordering always proceeds from left to right.

为了得到你想要的东西,你需要在 order by 子句中填充数字部分,比如:

To get what you want, you need to pad the numeric portion in your order by clause, something like:

 var result = partNumbers.OrderBy(x => PadNumbers(x));

其中 PadNumbers 可以定义为:

public static string PadNumbers(string input)
{
    return Regex.Replace(input, "[0-9]+", match => match.Value.PadLeft(10, '0'));
}

这会为输入字符串中出现的任何数字(或多个数字)填充零,以便 OrderBy 看到:

This pads zeros for any number (or numbers) that appear in the input string so that OrderBy sees:

ABC0000000010
ABC0000000001
...
AB0000000011

填充仅发生在用于比较的键上.结果中保留原始字符串(无填充).

The padding only happens on the key used for comparison. The original strings (without padding) are preserved in the result.

请注意,此方法假定输入中的数字有最大位数.

Note that this approach assumes a maximum number of digits for numbers in the input.

这篇关于使用 LINQ 进行字母数字排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 10:50