Hi Guys good day. What is the best way to sort a file version?
ie
4.06.045.07
3.06.045.07
4.12.45.074
4.06.04.207
so it would be this order:
3.06.045.07
4.06.04.207
4.06.045.07
4.12.45.074
Any inputs are much appreciated.
thanks.
Printable View
Hi Guys good day. What is the best way to sort a file version?
ie
4.06.045.07
3.06.045.07
4.12.45.074
4.06.04.207
so it would be this order:
3.06.045.07
4.06.04.207
4.06.045.07
4.12.45.074
Any inputs are much appreciated.
thanks.
Create Version objects and create an IComparer to compare them:Note that you can alter the way the versions are compared if you want but 045 is 45 and that's how it will be treated because version components and numbers and leading zeroes on numbers are meaningless. If you want to keep your leading zeroes then Version.ToString won't do it and this IComparer will ignore them in any comparisons. You could define your own version class if you wanted, or you you could just make your IComparer more complex and have it break up the string internally.Code:public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List<Version> versionList = new List<Version>();
versionList.Add(new Version("4.06.045.07"));
versionList.Add(new Version("3.06.045.07"));
versionList.Add(new Version("4.12.45.074"));
versionList.Add(new Version("4.06.04.207"));
versionList.Sort(new VersionComparer());
foreach (Version ver in versionList)
{
MessageBox.Show(ver.ToString());
}
}
}
public class VersionComparer : IComparer<Version>
{
int IComparer<Version>.Compare(Version x, Version y)
{
int result = x.Major - y.Major;
if (result == 0)
{
result = x.Minor - y.Minor;
}
if (result == 0)
{
result = x.Build - y.Build;
}
if (result == 0)
{
result = x.Revision - y.Revision;
}
return result;
}
}
Thanks JM. :)