Search code examples
c#linqsystem.version

system.version more than 3 decimal points c#


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


Solution

  • 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, f.e.:

    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