How can I sort a string of text followed by a number using LINQ

c#, linq

Solution

It's because you are sorting them as strings, and for strings 11 comes before 2. You'll need to parse the `ShortTitle` to give you the (I'm assuming) `int` value at the end, and sort by that.

Your LINQ query can be changed to this for it to work:

var query = _cityRepository.GetAll(
           .OrderBy(item => item.RowKey.Substring(0, 4))
           .ThenBy(item => item.ShortTitle.Split('-').First())
           .ThenBy(item => Convert.ToInt16(item.ShortTitle.Split().Last()));

Problem

I have been using the following sort: ``` var query = _cityRepository.GetAll( .OrderBy(item => item.RowKey.Substring(0, 4)) .ThenBy(item => item.ShortTitle) ``` However I am having a problem because my ShortTitle looks like this: ``` Liverpool - 1 Liverpool - 2 ... Liverpool - 9 Liverpool - 10 Liverpool - 11 West Kirby - 1 West Kirby - 8 West Kirby - 12 ``` When I sort this using LINQ it comes in the order ``` Liverpool - 1 Liverpool - 11 Liverpool - 12 Liverpool - 2 West Kirby - 1 West Kirby - 12 West Kirby - 8 ``` The ShortTitle is always a string of words followed by a single hyphen and then a number. Is there a way I can get this to sort correctly?

Original source

Related problems