CSharp · Console
// RE: https://stackoverflow.com/q/75986766/1690217
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Console.WriteLine("Demo LexicographicToAlphaNumeric Sorting:");
var tests = new string [] {
"Bird 10",
"Bird 2",
"Bird 1",
"20Lions",
"5Lions",
"red10blue",
"Red9blue",
"red100Blue"
};
foreach(var x in tests.Select(x => new { Value=x, SortKey = LexicographicToAlphaNumeric(x)}).OrderBy(x => x.SortKey))
Console.WriteLine("{0} ({1})", x.Value.PadRight(15), x.SortKey);
Console.WriteLine();
Console.WriteLine("Demo longer numberics");
Console.WriteLine( LexicographicToAlphaNumeric("Bird 10000",7));
Console.WriteLine( LexicographicToAlphaNumeric("Bird 2000",7));
Console.WriteLine( LexicographicToAlphaNumeric("Bird 1000",7));
}
/// <summary> Pad numeric portions of a string to allow natural lexicographic sorting to behave like numerical sorting for the numeric components</summary>
/// <remarks> using the same categorization technique to simplify the explanation, have not tested this for performance, and I just love the name ;)</remarks>
/// <param name="value">The string value to pad the numbers in</param>
/// <param name="size">The number of digits to pad the numeric values out to, by default 3 digits</param>
/// <returns> alphanumeric string that so that "Bird 2" becomes "Bird 02", to allow "Bird 2" to be sorted before "Bird 10"<returns>
public static string LexicographicToAlphaNumeric(string value, int size = 3)
{
// exit if there is nothing to process.
if (String.IsNullOrWhiteSpace(value)) return value;
int groupId = 0;
bool isNumberGroup = false;
return String.Join("", value.Select((c, index) => {
var isNumber = Char.IsDigit(c); // NOTE: will not support decimals
if( isNumber != isNumberGroup)
{
groupId ++;
isNumberGroup = isNumber;
}
return new { c, isNumber, groupId, index };
})
.GroupBy(c => c.groupId)
.Select(g => g.First().isNumber ? new string(g.Select(x => x.c).ToArray()).PadLeft(size, '0') : new string(g.Select(x => x.c).ToArray())));
}
}