How to OrderBy an integer in a string field in a Linq query

Came up with a simple trick to fix this: First order by length and then normaly.

dataFromDB.OrderBy(o => o.StringHoldingAnInt.Length).ThenBy(o => o.StringHoldingAnInt)

This is all done in DB and doesn't load into memory.


It's possible to do it on the DB side. The idea is taken from here. So it does sorting by properly formatted string(zero chars are added to the left and then needed amount of chars is taken from the right)

myControl.DataSource = dataFromDB
    .OrderBy(o =>  DbFunctions.Right("00000" + o.StringHoldingAnInt, 7));

This won't be nearly as efficient because you're not harnessing the database query to filter your results, but this would basically query for all data, then filter on the client.

myControl.DataSource = dataFromDB.ToList().OrderBy(o => int.Parse(o.StringHoldingAnInt));