csharp C#数字字符串排序orderby的问题解决
一般情况下 您使用
strs.OrderBy(n=>n) 得出的结论是 1, 11,111,2,22,222
想要得出 1,2,11,22,111,222 咋办?
源码送上
static void Main() { SemiNumericComparer comp = new SemiNumericComparer(); List<string> strs = new List<string>(){"11", "12", "1:"}; foreach(string str in strs.OrderBy(n => n, comp)) Console.writeLine(str); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | public class SemiNumericComparer : IComparer< string > { public int Compare( string s1, string s2) { if (IsNumeric(s1) && IsNumeric(s2)) { if (Convert.ToInt32(s1) > Convert.ToInt32(s2)) return 1; if (Convert.ToInt32(s1) < Convert.ToInt32(s2)) return -1; if (Convert.ToInt32(s1) == Convert.ToInt32(s2)) return 0; } if (IsNumeric(s1) && !IsNumeric(s2)) return -1; if (!IsNumeric(s1) && IsNumeric(s2)) return 1; return string .Compare(s1, s2, true ); } public static bool IsNumeric( object value) { try { int i = Convert.ToInt32(value.ToString()); return true ; } catch (FormatException) { return false ; } } } |
代码摘自网络。
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决