Sorting Strings Numerically While Preserving Alphabetical Order
To resolve the issue of sorting strings that are numeric but cannot be converted to integers, you can implement a custom sorting algorithm. Here's how to do it:
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); }
This approach allows you to sort strings alphabetically while accounting for numeric values, resulting in the desired output:
007 90 bob lauren paul
The above is the detailed content of How to Sort Strings Numerically While Maintaining Alphabetical Order?. For more information, please follow other related articles on the PHP Chinese website!