名称包含字母和数字时的排序

Sah*_*hil 5 c# linq arrays sorting

我有以下数组

[0] = GB_22_T0001.jpg
[1] = GB_22_T0002.jpg
[2] = GB_22_T0003.jpg
[3] = GB_22_T0006.jpg
[4] = GB_22_T0007.jpg
[5] = GB_22_T0008.jpg
[6] = GB_22_T0009.jpg
[7] = GB_22_T00010.jpg
[8] = GB_22_T00011.jpg
[9] = GB_22_T00012.jpg
[10] = GB_22_T00013.jpg
Run Code Online (Sandbox Code Playgroud)

我已将此项目放在列表框中,并注意到“ GB_22_T00010”紧跟在“ GB_22_T0001”之后而不是“ GB_22_T0002”之后

似乎是c#的常见问题,但找不到该问题的常见答案。

我尝试使用Array.sort(data)对数组进行排序,还尝试了LinQ的OrderBy方法,但是它们都没有帮助。

有人解决吗?

小智 5

这是我对具有字母和数字字符的字符串进行排序的代码。

首先,这个扩展方法:

public static IEnumerable<string> AlphanumericSort(this IEnumerable<string> me)
{
    return me.OrderBy(x => Regex.Replace(x, @"\d+", m => m.Value.PadLeft(50, '0')));
}
Run Code Online (Sandbox Code Playgroud)

然后,只需在代码中的任何位置使用它,如下所示:

List<string> test = new List<string>() { "The 1st", "The 12th", "The 2nd" };
test = test.AlphanumericSort();
Run Code Online (Sandbox Code Playgroud)

它是如何工作的?通过用零替换:

  Original  | Regex Replace |      The      |   Returned
    List    | Apply PadLeft |    Sorting    |     List
            |               |               |
 "The 1st"  |  "The 001st"  |  "The 001st"  |  "The 1st"
 "The 12th" |  "The 012th"  |  "The 002nd"  |  "The 2nd"
 "The 2nd"  |  "The 002nd"  |  "The 012th"  |  "The 12th"
Run Code Online (Sandbox Code Playgroud)

适用于倍数:

 Alphabetical Sorting | Alphanumeric Sorting
                      |
 "Page 21, Line 42"   | "Page 3, Line 7"
 "Page 21, Line 5"    | "Page 3, Line 32"
 "Page 3, Line 32"    | "Page 21, Line 5"
 "Page 3, Line 7"     | "Page 21, Line 42"
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助。


Tim*_*ter 2

GB_22_T0001是一个字符串而不是数字。所以它是按字典顺序而不是数字排序的。因此,您需要将字符串的一部分解析int为.

var ordered = array.Select(Str => new { Str, Parts=Str.Split('_') })
                   .OrderBy(x => int.Parse(x.Parts.Last().Substring(1))) 
                   .Select(x => x.Str);
Run Code Online (Sandbox Code Playgroud)

Split('_')将字符串拆分为分隔符上的子字符串_。最后一个子字符串包含您的数值。然后我通常String.Substring只采用数字部分(删除开头Tint.Parse。该整数用于Enumerable.OrderBy. 最后一步是仅选择字符串而不是匿名类型。

编辑:这是支持的版本Paths

var ordered = array.Select(str => { 
    string fileName = Path.GetFileNameWithoutExtension(str);
    string[] parts =  fileName.Split('_');
    int number = int.Parse(parts.Last().Substring(1));
    return new{ str, fileName, parts, number };
 })
.OrderBy(x => x.number)
.Select(x => x.str);
Run Code Online (Sandbox Code Playgroud)