Linq: order list of versions

If we have a queryable of entities with a version field (for example a “Code” field), when we try to order the the result the processing is carried out based on the comparison of strings:

class VersioField
{
  public string Code { get; set; }
}

private void VersionOrder()
{
  List<VersioField> lst1 = new List<VersioField>()
  {
    new VersioField(){Code = "1.1.1" },
    new VersioField(){Code = "1.3.1" },
    new VersioField(){Code = "1.1.2" },
    new VersioField(){Code = "1.2.3" },
    new VersioField(){Code = "1.2.0" },
    new VersioField(){Code = "1.1.3" },
    new VersioField(){Code = "1.1.4" },
    new VersioField(){Code = "1.1.10"},
    new VersioField() { Code = "1.2.1" },
    new VersioField() { Code = "1.1.11" } 
  };

  var result1 = lst1.OrderBy(x  => x.Code);
  foreach (var elem in result1)
  {
    Debug.WriteLine(elem.Code);
  }
}
Output:
1.1.1
1.1.10
1.1.11
1.1.2
1.1.3
1.1.4
1.2.0
1.2.1
1.2.3
1.3.1

If we want an order based on the comparison of versions we can use the Parse method of the System.Version class (that converts the string representation of a version number to an equivalent Version object) in this way:

var result1 = lst1.OrderBy(x => Version.Parse(x.Code));
foreach (var elem in result1)
{
  Debug.WriteLine(elem.Code); 
}
Output:
1.1.1
1.1.2
1.1.3
1.1.4
1.1.10
1.1.11
1.2.0
1.2.1
1.2.3
1.3.1

The same method could be used  with a list which represents a list of version strings:

private void VersionOrder()
{ 
  List<string> lst2 = new List<string>();
  lst2.Add("1.1.1");
  lst2.Add("1.3.1");
  lst2.Add("1.1.2");
  lst2.Add("1.2.3");
  lst2.Add("1.2.0");
  lst2.Add("1.1.3");
  lst2.Add("1.1.4");
  lst2.Add("1.1.10");
  lst2.Add("1.2.1");
  lst2.Add("1.1.11");

  var result2 = lst2.ToList().OrderBy(x => Version.Parse(x));
  foreach (var elem in result2)
  {
    Debug.WriteLine(elem);
  }
}
Output:
1.1.1
1.1.2
1.1.3
1.1.4
1.1.10
1.1.11
1.2.0
1.2.1
1.2.3
1.3.1

 

 

Leave a comment