Skip to content

Instantly share code, notes, and snippets.

@ironpython2001
Last active May 5, 2022 08:04
Show Gist options
  • Save ironpython2001/c2e2cbf5dd742b8c0605e9ab57bbd913 to your computer and use it in GitHub Desktop.
Save ironpython2001/c2e2cbf5dd742b8c0605e9ab57bbd913 to your computer and use it in GitHub Desktop.
version number comparison in c#
//Version 1 Version 2 Result
//1.11.17 2.3.5 2.3.5
//2.1 2.1.3 2.1.3
//2.3.5 2.4 2.4.0
//3.1 2.4 3.1.0
//3.3 3.2.9 3.3.0
//7.2.71 7.2.71 7.2.71
string s1 = "2.1";
string s2 = "2.11.3";
var cnt1 = s1.Count(x => x == '.');
if (cnt1 < 1)
s1 = s1 + ".0";
var cnt2 = s2.Count(x => x == '.');
if (cnt2 < 1)
s2 = s2 + ".0";
var lst1 = s1.Split('.').ToList(); ;
var lst2 = s2.Split('.').ToList(); ;
var lst3 = new List<string>();
lst1.ForEach(x => lst3.Add(x));
lst2.ForEach(x => lst3.Add(x));
string longest = lst3.OrderByDescending(s => s.Length).First();
string s3 = string.Empty;
foreach (var i in lst1)
{
s3 = s3 + i.PadLeft(longest.Length, '0') + ".";
}
string s4 = string.Empty;
foreach (var i in lst2)
{
s4 = s4 + i.PadLeft(longest.Length, '0') + ".";
}
List<string> lst = new List<string> { s3, s4 };
var res1 = lst.OrderByDescending(x => x).First();
Console.WriteLine(res1.Remove(res1.Length-1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment