例如:
这个数组:
a 2
a 10
a
应该在排序之后:
a
a 2
a 10
我尝试了这个,但它不起作用:顺序错误。
...
.OrderBy(s => s.name)
.ThenBy(s => {
var stringNumber = Regex.Match(s.name, @"\d+").Value;
return string.IsNullOrEmpty(stringNumber)
? 0
: int.Parse(stringNumber);
});
最佳答案
我建议显式提取条件:正则表达式中的 name
和 number
组:
var list = new List<string>() {
"a",
"a 4",
"b 1",
"a 2",
"a 11"
};
var result = list
.Select(item => new {
value = item,
match = Regex.Match(item, @"^(?<name>.*?)\s*(?<number>[0-9]*)$"),
})
.OrderBy(item => item.match.Groups["name"].Value)
.ThenBy(item => item.match.Groups["number"].Value.Length)
.ThenBy(item => item.match.Groups["number"].Value)
.Select(item => item.value);
测试:
Console.WriteLine(string.Join(Environment.NewLine, result));
结果:
a
a 2
a 4
a 11
b 1
关于c# - linq - 字符串列表 - 仅按字母排序,然后按数字排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47919760/