I am currently receiving the following error - "Version string portion was too short or too long"
When using this statement -
records = records.OrderBy(r => new Version(r.RefNo)).ToList();
To order a list of string's called RefNo. It fails on 25.1.2.1.2 so i assume it is because it has four decimal points? as it works ok with 3....
Is the max four deciaml points for system.version?
Thanks
A Version
can only have 4 parts:
major, minor, build, and revision, in that order, and all separated by periods.
That's why your approach fails. You could create an extension-method which handles this case, fe:
public static Version TryParseVersion(this string versionString)
{
if (string.IsNullOrEmpty(versionString))
return null;
String[] tokens = versionString.Split('.');
if (tokens.Length < 2 || !tokens.All(t => t.All(char.IsDigit)))
return null;
if (tokens.Length > 4)
{
int maxVersionLength = tokens.Skip(4).Max(t => t.Length);
string normalizedRest = string.Concat(tokens.Skip(4).Select(t => t.PadLeft(maxVersionLength, '0')));
tokens[3] = $"{tokens[3].PadLeft(maxVersionLength, '0')}{normalizedRest}";
Array.Resize(ref tokens, 4);
}
versionString = string.Join(".", tokens);
bool valid = Version.TryParse(versionString, out Version v);
return valid ? v : null;
}
Now you can use it in this way:
records = records
.OrderBy(r => r.RefNo.TryParseVersion())
.ToList();
With your sample this new version string will be parsed(successfully): 25.1.2.12
See MSDN
Costructor public Version(string version)
A string containing the major, minor, build, and revision numbers, where each number is delimited with a period character ('.').
Makes a total of 4 numbers.
Means the string is limited to 4 numbers, 5 lead to an error.
Also the costructors with int
's as parameters only support 1 to 4 parameters.
sorry for the late reply but here is the finished extension method i used with a couple of alterations -
public static Version ParseRefNo(this string refNoString)
{
if (string.IsNullOrEmpty(refNoString))
return null;
String[] tokens = refNoString.Split('.');
if (tokens.Length < 2 || !tokens.All(t => t.All(char.IsDigit)))
return null;
if (tokens.Length > 4)
{
int maxVersionLength = tokens.Skip(4).Max(t => t.Length);
string normalizedRest = string.Concat(tokens.Skip(4).Select(t => t.PadLeft(maxVersionLength, '0')));
tokens[3] = $"{tokens[3].PadLeft(maxVersionLength, '0')}{normalizedRest}";
Array.Resize(ref tokens, 4);
}
refNoString = string.Join(".", tokens);
Version v = null;
bool valid = Version.TryParse(refNoString, out v);
return valid ? v : null;
}
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.