Sorting Strings Alphabetically and Numerically with Custom Comparison
This question presents a challenge in sorting an array of string numbers alphabetically while considering their numeric values. To achieve this, a custom comparer must be implemented to override the default string comparison.
Implementation Details
The code below demonstrates how to implement this sorting:
using System; using System.Collections.Generic; using System.Linq; namespace StringSort { class Program { static void Main(string[] args) { // Input array of string numbers string[] things = new string[] { "105", "101", "102", "103", "90" }; // Sort using custom comparer IEnumerable<string> sortedThings = things.OrderBy(x => x, new SemiNumericComparer()); // Print sorted array foreach (var thing in sortedThings) { Console.WriteLine(thing); } } public class SemiNumericComparer : IComparer<string> { // Check if a string is numeric public bool IsNumeric(string value) { return int.TryParse(value, out _); } // Compare two strings public int Compare(string s1, string s2) { const int S1GreaterThanS2 = 1; const int S2GreaterThanS1 = -1; // Check if both strings are numeric var IsNumeric1 = IsNumeric(s1); var IsNumeric2 = IsNumeric(s2); if (IsNumeric1 && IsNumeric2) { int i1 = Convert.ToInt32(s1); int i2 = Convert.ToInt32(s2); return i1.CompareTo(i2); } // If one string is numeric and the other is not, consider the numeric string greater if (IsNumeric1) return S2GreaterThanS1; if (IsNumeric2) return S1GreaterThanS2; // Otherwise, perform a case-insensitive alphabetical comparison return string.Compare(s1, s2, true, CultureInfo.InvariantCulture); } } } }
Custom Comparer Logic
The SemiNumericComparer class defines the comparison logic for strings. It first checks if both strings are numeric using the IsNumeric method. If both are numeric, it compares them numerically. If only one string is numeric, it considers the numeric string greater. For non-numeric strings, it performs a case-insensitive alphabetical comparison.
When using this comparer with Enumerable.OrderBy, the array of string numbers will be sorted first by numeric value, then alphabetically for non-numeric strings. The output of the example above will be:
90 101 102 103 105
The above is the detailed content of How to Sort Strings Alphabetically and Numerically Using a Custom Comparer in C#?. For more information, please follow other related articles on the PHP Chinese website!