4

I have the following list in a table

Name
Server1
Server2
Server3
Server4
Server5
Server6
Server7
Server8
Server9
Server10
Server11
Server12

only problem is my linq satement orderby Name ascending puts them like the below

Server1
Server10
Server11
Server12
Server2
Server3
Server4
Server5
Server6
Server7
Server8
Server9

is there anyway to stop this?

Thanks

AlexW
  • 2,843
  • 12
  • 74
  • 156

1 Answers1

4

For this special use case, you can either order by length and then name or parse the number and order by it:

// 1st alternative
servers.OrderBy(s => s.Length).OrderBy(s => s.Name);

// 2nd alternative
servers.OrderBy(s => Int32.Parse(s.Substring(6)));
Matten
  • 17,365
  • 2
  • 42
  • 64
  • 1
    Well, not in linq to entities. Got to enumerate first. Linq to entities won't appreciate Int32.Parse. – Raphaël Althaus Nov 07 '13 at 15:51
  • +1 for the "2nd alternative" because it is a viable solution. – Travis J Nov 07 '13 at 15:51
  • 1
    Does linq to entities support .Substring in a store expression? Since which version? – danludwig Nov 07 '13 at 15:52
  • @RaphaëlAlthaus You're right, but the example looks like the set of results isn't too big and all data is fetched, anyway. Therefore I won't mind a second enumeration, *in this special use case*. – Matten Nov 07 '13 at 15:54