Search code examples
c#linqlistsorting

Sort List by string converted to int


I have a list of Int saved as String and I would like to order them. I came up with the following solution:

sortList = sortList.OrderByDescending(x => Convert.ToInt32(x.Number)).ToList();

It works perfectly, but only if the list only contains numbers. For example, if there is one item that is a string like "???" the sorting totally fails.

Expectation:

['313', '309', '119', '49', '???']

Result:

['309' '49' '313' '119' '???']

Solution

  • So you need to use int.TryParse() and return a low value for invalid strings:

    sortList = sortList.OrderByDescending(x =>
        {
            int i;
            return int.TryParse(x.Number, out i) ? i : int.MinValue;
        });
    

    I use OrderByDescending instead of OrderBy as the expected result you showed is in descending order.