13

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;
Kieron
  • 25,894
  • 15
  • 74
  • 118

2 Answers2

10

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.

Andrew Hare
  • 333,516
  • 69
  • 632
  • 626
2

I'm only a few years late to the party, but I was just trying to solve a similar problem and this worked for me. Hope someone else finds this helpful.

Say you have your strings in a List, try something like this:

List<string> projects = new List<string>
{
    "Project 1",
    "Project 10",
    "Project 2"
};
//Sort by a substring of the string value which omits the non-numeric characters
IEnumerable<string> sorted = projects.OrderBy(p => p.Substring(p.IndexOf(' ') + 2, p.Length - (p.IndexOf(' ') + 2)));
  • This is pretty good, I could also take advantage of a known pattern up front. Note that substring has a method that takes start only, and goes to the end `p => p.Substring(p.IndexOf(" ") + 1))` (and it's a double-quote, and +1 instead of +2) – goodeye Mar 17 '19 at 18:34