Extension method for StringComparison
or any IComparer<string>
that adds support for natural sorting (e.g. "abc1", "abc2", "abc10" instead of "abc1", "abc10", "abc2").
The library is written in C# and released with an MIT license, so feel free to fork or use commercially.
Any feedback is appreciated, please visit the issues page or send me an e-mail.
Binaries of the last build can be downloaded on the AppVeyor CI page of the project.
The library is also published on NuGet.org, install using:
PM> Install-Package NaturalSort.Extension
NaturalSort.Extension is built for .NET Standard 1.3, .NET 6, and .NET 8 and is signed to allow use in projects that use strong names.
The recommended method for best results is to create the comparer by using the StringComparison
enum.
var sequence = new[] { "img12.png", "img10.png", "img2.png", "img1.png" };
var ordered = sequence.OrderBy(x => x, StringComparison.OrdinalIgnoreCase.WithNaturalSort());
// ordered will be "img1.png", "img2.png", "img10.png", "img12.png"
For more information about natural sort order, see:
The NaturalSortComparer
created using the extension method is a IComparer<string>
, which you can use in all the places that accept IComparer<string>
(e.g. OrderBy
, Array.Sort
, ...)
If you wish, you can be more explicit by not using the .WithNaturalSort()
extension method, and using the constructor directly:
new NaturalSortComparer(StringComparison.OrdinalIgnoreCase)
Note that if you are using a custom IComparer<string>
(or StringComparer
), you can also use that instead of the StringComparison
enum. However, if you use StringComparison
, it should perform better as it avoids constructing substrings.
If you're using Microsoft.Data.Sqlite, it's also possible to use the extension as collation for use in your SQLite queries.
You can register the collation on a SQLite connection as follows (more info in docs):
private static readonly NaturalSortComparer NaturalComparer = new(StringComparison.InvariantCultureIgnoreCase);
/* ... */
SqliteConnection conn;
conn.CreateCollation("NATURALSORT", (x, y) => NaturalComparer.Compare(x, y));
Then you can use the collation to achieve natural sorting in your SQL query:
SELECT * FROM Customers
ORDER BY Name COLLATE NATURALSORT;