Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Created April 29, 2023 12:51
Show Gist options
  • Save karenpayneoregon/54cf90f8d08a28fded0ebc602fa333b6 to your computer and use it in GitHub Desktop.
Save karenpayneoregon/54cf90f8d08a28fded0ebc602fa333b6 to your computer and use it in GitHub Desktop.
C# code which provides a natural sort for strings ending with numbers
using System.Runtime.InteropServices;
namespace YourNamespaceGoesHere;
public class NaturalStringComparer : Comparer<string>
{
[DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string x, string y);
public override int Compare(string x, string y)
=> StrCmpLogicalW(x, y);
}
using YourNamespaceGoesHere.Classes;
namespace YourNamespaceGoesHere;
internal partial class Program
{
static void Main(string[] args)
{
StandardSortSample();
NaturalSortSample();
Console.ReadLine();
}
private static void NaturalSortSample()
{
Print("Natural sort");
var fileNames = FileNames();
fileNames.Sort(new NaturalStringComparer());
foreach (var item in fileNames)
{
Console.WriteLine(item);
}
Console.WriteLine();
List<string> values = new() { "A11", "A9", "A1", "A22" };
values.Sort(new NaturalStringComparer());
foreach (var item in values)
{
Console.WriteLine(item);
}
}
private static void StandardSortSample()
{
Print("Standard sort");
var fileNames = FileNames();
foreach (var item in fileNames)
{
Console.WriteLine(item);
}
Console.WriteLine();
List<string> values = new List<string>() { "A11", "A9", "A1", "A22" };
foreach (var item in values)
{
Console.WriteLine(item);
}
}
private static List<string> FileNames() =>
new()
{
"Example12.txt", "Example2.txt", "Example3.txt", "Example4.txt",
"Example5.txt", "Example6.txt", "Example7.txt", "Example8.txt",
"Example9.txt", "Example10.txt", "Example11.txt", "Example1.txt",
"Example13.txt", "Example14.txt", "Example15.txt", "Example16.txt",
"Example17.txt", "Example18.txt", "Example19.txt", "Example20.txt"
};
private static void Print(string text)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(text);
Console.ResetColor();
Console.WriteLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment