Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a custom sorting method for sorting version numbers using C#? [duplicate]

Tags:

c#

linq

I have a list versionNumbers =

v1.6.4
v2.1.19
v2.1.20
v2.10.00
v2.2.00
v2.2.01
v2.3.00
v2.4.00
v2.6.00
v2.4.01

After 2.9.00, the version should be 3.0.xx. But I have 2.10.00 and forward.

I tried System Sort() method and Orderby with Version.parse() method. But they gave me wrong output:

v1.6.4
v2.1.19
v2.1.20
v2.10.00
v2.2.00
v2.2.01
v2.3.00
v2.4.00
v2.4.01

I am expecting 2.10.00 in the end and so on. What is the best way to sort such version numbering in C# and linq?

like image 785
Walter Avatar asked Jan 23 '26 04:01

Walter


1 Answers

Use a List<Version>, then you can simple use list.Sort(). To get a version from a string use Version.Parse. Since you have a v in front you need to remove it:

List<string> versionStringList = new() {
    "v1.6.4",
    "v2.1.19",
    "v2.1.20",
    "v2.10.00",
    "v2.2.00",
    "v2.2.01",
    "v2.3.00",
    "v2.4.00",
    "v2.6.00",
    "v2.4.01"
};

List<Version> versionList = versionStringList
    .Select(s => Version.Parse(s.TrimStart('v', 'V')))
    .ToList();

versionList.Sort();

Result in debugger:

-       versionList Count = 10  System.Collections.Generic.List<System.Version>
+       [0] {1.6.4}  System.Version
+       [1] {2.1.19} System.Version
+       [2] {2.1.20} System.Version
+       [3] {2.2.0}  System.Version
+       [4] {2.2.1}  System.Version
+       [5] {2.3.0}  System.Version
+       [6] {2.4.0}  System.Version
+       [7] {2.4.1}  System.Version
+       [8] {2.6.0}  System.Version
+       [9] {2.10.0} System.Version

If you also don't know how to convert the Version afterwards to a formatted string, where the build number has always at least two digits, you can use this approach:

private static string VersionToString(Version v)
     => $"v{v.Major}.{v.Minor}.{v.Build.ToString("D2")}";

versionStringList = versionList.Select(VersionToString).ToList();
like image 83
Tim Schmelter Avatar answered Jan 25 '26 17:01

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!