I'm working on an Update-Tool for a program my company developed. To update the programm I need to execute some SQL-Scripts. These scripts must have the right order (of course). I have a List. The SqlScriptModel has a 'Name' Property, I used to sort the list. The SQL-Scripts-Name start with the Programm-Version (example: 5.8.1.0). At the moment my 'sorted' list looks like this:
5.8.0.1 - Update Script
5.8.0.10 - Update Script
5.8.0.11 - Update Script
5.8.0.2 - Update Script
Of course the 5.8.0.10
script needs to be executed after the 5.8.0.2
script.
My code looks like this:
SqlScriptList.Sort((x, y) => string.Compare(x.Name, y.Name));
Has somebody already had the same problem? Or has a link to a valid solution? I would be very thankful!
Just rename your files so that all version substrings are of the same length. Pad the last part of the version with zeroes like this:
5.8.0.01 - Update Script
5.8.0.02 - Update Script
5.8.0.10 - Update Script
5.8.0.11 - Update Script
If you don't want to do this, in the code you can convert the version string to a number and then sort based on that number:
string version = "5.8.0.10";
int fullVersionNumber =
version
.Split(new char[] { '.' })
.Select(int.Parse)
.Aggregate((first, second) => first * 100 + second);
// fullVersionNumber = 5080010
You can make a function out of this:
public static int GetNumericVersion(string fileName)
{
string version = fileName.Split(new char[] { ' ' })[0];
int fullVersionNumber =
version
.Split(new char[] { '.' })
.Select(int.Parse)
.Aggregate((first, second) => first * 100 + second);
return fullVersionNumber;
}
And use it like this:
SqlScriptList.Sort(
(x, y) => GetNumericVersion(x.Name).CompareTo(GetNumericVersion(y.Name)));
Consider using Version class from .Net framework, it has a suitable compare operator.
Sample code:
List<Version> versions = new List<Version>();
List<string> versionStrings;
// get somehow, the list of version strings in "Version format" - nothing else except x.y.z.k
versionStrings = new List<string>(
new string[]{ "5.8.0.1",
"5.8.0.10",
"5.8.0.11",
"5.8.0.2" }
);
// pupulate list of Version from list of string
versionStrings.ForEach(str => versions.Add(new Version(str)));
//list is not orderded
versions.ForEach(ver => System.Diagnostics.Debug.WriteLine(ver));
// sort the list using the default Version comparison
versions.Sort();
// list is ordered
versions.ForEach(ver => System.Diagnostics.Debug.WriteLine(ver));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.