LINQ and a natural sort order

Kieron picture Kieron · Aug 24, 2009 · Viewed 10.3k times · Source

What's the easiest way to get a LINQ query (from an SQL database - does that matter?) to order strings naturally?

For example, I'm currently getting these results:

  • Project 1
  • Project 10
  • Project 2

What I'd like is to see is this:

  • Project 1
  • Project 2
  • Project 10

The query I'm using is this:

return from p in dataContext.Projects
    orderby p.Name
    select p;

Answer

Andrew Hare picture Andrew Hare · Aug 24, 2009

There is no built-in way to do this using the .NET framework but I would suggest that you read Natural Sorting in C# for a discussion on the topic and an open-source implementation.