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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With