如何使用C# Linq按特殊字符、数字、字母顺序排序字母数字字符串?
C# Linq 实现特殊字符优先的字母数字字符串排序
实现思路
核心逻辑是先按字符串首字符的类型划分优先级层级,再在同层级内按字符串自然排序:
- 优先级0:首字符为非字母数字的特殊字符(排在最前面)
- 优先级1:首字符为数字(中间层)
- 优先级2:首字符为字母(最后面)
代码实现
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main() { // 输入集合 var inputStrings = new List<string> { "Hello", "#Test", "@Red", "&While", "123@Test", "@123Test", "%54Sun", "Dom", "Left" }; // Linq排序逻辑 var sortedStrings = inputStrings .OrderBy(str => { char firstChar = str[0]; if (!char.IsLetterOrDigit(firstChar)) return 0; // 特殊字符组 else if (char.IsDigit(firstChar)) return 1; // 数字开头组 else return 2; // 字母开头组 }) .ThenBy(str => str) // 同组内按字符串自然排序 .ToList(); // 输出结果 foreach (var str in sortedStrings) { Console.WriteLine(str); } } }
自定义排序调整
如果需要和你给出的示例顺序完全匹配(特殊字符组内自定义排序),可以添加特殊字符的优先级映射,调整同组内的排序逻辑:
// 自定义特殊字符排序优先级字典 var charPriority = new Dictionary<char, int> { { '@', 0 }, { '%', 1 }, { '#', 2 }, { '&', 3 } }; var sortedStrings = inputStrings .OrderBy(str => { char firstChar = str[0]; if (!char.IsLetterOrDigit(firstChar)) return 0; else if (char.IsDigit(firstChar)) return 1; else return 2; }) .ThenBy(str => { char firstChar = str[0]; // 按自定义规则排序特殊字符,其余按Unicode值排序 return charPriority.TryGetValue(firstChar, out int priority) ? priority : (int)firstChar; }) .ThenBy(str => str) .ToList();
调整后即可得到你预期的排序结果。
内容的提问来源于stack exchange,提问作者vivek
相关产品推荐
相关产品推荐

