在保留字母顺序的情况下对字符串进行数字排序
要解决对数字但无法转换为整数的字符串进行排序的问题,您可以实现自定义排序算法。操作方法如下:
public class SemiNumericComparer : IComparer<string> { public static bool IsNumeric(string value) => int.TryParse(value, out _); public int Compare(string s1, string s2) { const int S1GreaterThanS2 = 1; const int S2GreaterThanS1 = -1; var isNumeric1 = IsNumeric(s1); var isNumeric2 = IsNumeric(s2); // Handle numeric comparisons if (isNumeric1 && isNumeric2) { var i1 = Convert.ToInt32(s1); var i2 = Convert.ToInt32(s2); return i1 > i2 ? S1GreaterThanS2 : (i1 < i2 ? S2GreaterThanS1 : 0); } // Handle mixed numeric and non-numeric comparisons if (isNumeric1) return S2GreaterThanS1; if (isNumeric2) return S1GreaterThanS2; // Handle alphabetical comparisons return string.Compare(s1, s2, true, CultureInfo.InvariantCulture); } }
string[] things = new string[] { "paul", "bob", "lauren", "007", "90", "101" }; foreach (var thing in things.OrderBy(x => x, new SemiNumericComparer())) { Console.WriteLine(thing); }
此方法允许您在考虑数字的同时按字母顺序对字符串进行排序值,产生所需的输出:
007 90 bob lauren paul
以上是如何在保持字母顺序的同时对字符串进行数字排序?的详细内容。更多信息请关注PHP中文网其他相关文章!