Wednesday, February 26, 2025

.NET 10 Preview 1.0: Numeric Ordering for String Comparison

After so much of waiting, the first preview of .NET 10 is now available. This comes with new .NET libraries, some new C# 14 features and many more.

In this post let's have a look a new .NET library feature that was initially requested back in 2015, and finally that's made into .NET 10.

Consider the following list of strings.
List<string> strings =
[
    "3",
    "5",
    "05",
    "10",
    "11"
];
If you order these by doing something below,
IOrderedEnumerable<string> orderedStrings = strings.Order();
The order would be,
05
10
11
3
5
These are lexicographically ordered. But numerically, "3" is less than "05" and also "5" and "05" are equal.

Now we have new NumericOrdering comparer for strings.
// The new numerical string comparer
StringComparer numericStringComparer =  StringComparer.Create(CultureInfo.CurrentCulture, CompareOptions.NumericOrdering);
IOrderedEnumerable<string> orderedStrings = strings.Order(numericStringComparer);
And now the output would be as we expect.
3
5
05
10
11
Love it.

Read more:

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment