Search code examples
c#stringlistsortingicomparable

C# How to sort list of objects with string values


I need sort list of string values using IComparable:

10.1, 10.10, 10.11, 10.2, 10.3 

Expected result:

10.1, 10.2, 10.3, 10.10, 10.11

Tried to use list.Sort but didn't work


Solution

  • Basically what you want to do is to sort by the number after the decimal point in the string. So, take only that part, convert it to a number and then sort. Using Comparer it will look like

    List<string> values = new List<string> { "10.1", "10.10", "10.11", "10.2", "10.3" };
    
    values.Sort((x, y) => int.Parse(x.Split('.')[1]).CompareTo(int.Parse(y.Split('.')[1])));
    

    Or using linq it will look like:

    var result = values.OrderBy(value => int.Parse(value.Split('.')[1]));
    

    In the case you want to first sort by the second part and then by the first you can do:

    var result = values.OrderBy(value => int.Parse(value.Split('.')[0]))
                       .ThenBy(value => int.Parse(value.Split('.')[1]))
                       .ToList();
    

    keep in mind that this solution is naive and assumes all your values have a . and that the 2 parts of it can be parsed into int - If it is not the case then you can use TryParse