C# How to sort version number

T.Zacks 3,986 Reputation points
2023-01-19T20:17:40.7766667+00:00

Suppose we have series of version number stored in List<string>. i need to sort those version number ascending or descending order. i have the done the job this way. my code attached.

var ver = new List<string>();
ver.Add("3.5");
ver.Add("3.15");
ver.Add("3.10");
ver.Add("3.1");

var OrderData = ver.Select(x => new
{
	version = x.ToString(),
	vorder = x.ToString().Replace(".", "")
}).OrderByDescending(y => Convert.ToInt32(y.vorder)).ToList();

without using LINQ how to achieve this task. looking for sample code. Thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Dimple Rane 906 Reputation points
    2023-01-19T20:21:46.66+00:00

    Without using LINQ, you can use the List<T>.Sort() method to sort the version numbers in ascending or descending order. Here's an example of how you can do this:

    var ver = new List<string>();
    ver.Add("3.5");
    ver.Add("3.15");
    ver.Add("3.10");
    ver.Add("3.1");
    ver.Sort((x, y) =>
    {
        var xparts = x.Split('.');
        var yparts = y.Split('.');
        for (int i = 0; i < xparts.Length; i++)
        {
            if (i >= yparts.Length)
                return 1;
            var xval = int.Parse(xparts[i]);
            var yval = int.Parse(yparts[i]);
            if (xval != yval)
                return xval.CompareTo(yval);
        }
        return xparts.Length.CompareTo(yparts.Length);
    });
    

    The above code sorts the version numbers in ascending order.

    To sort in descending order you can use ver.Reverse() after sorting the list.

    ver.Sort((x, y) =>
    {
        var xparts = x.Split('.');
        var yparts = y.Split('.');
        for (int i = 0; i < xparts.Length; i++)
        {
            if (i >= yparts.Length)
                return 1;
            var xval = int.Parse(xparts[i]);
            var yval = int.Parse(yparts[i]);
            if (xval != yval)
                return xval.CompareTo(yval);
        }
        return xparts.Length.CompareTo(yparts.Length);
    });
    ver.Reverse();
    

    This way you can achieve the same thing without using LINQ.

    1 person found this answer helpful.

  2. Karen Payne MVP 35,386 Reputation points
    2023-01-25T23:04:14.0166667+00:00

    Perhaps using the version class is a better option

    versions

    List<Version> versions = new()
    {
        new (3, 5),
        new (3, 1),
        new (3, 15),
        new (3,10)
    };
    
    versions = versions
        .OrderBy(x => x.Major)
        .ThenBy(x => x.Minor)
        .ToList();