在保留字母順序的情況下對字串進行數字排序
要解決對數字但無法轉換為整數的字串進行排序的問題,您可以實作自訂排序演算法。操作方法如下:
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中文網其他相關文章!