LINQ and a natural sort order [duplicate]
-
19-09-2019 - |
Question
This question already has an answer here:
- Natural Sort Order in C# 16 answers
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;
Solution
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.
OTHER TIPS
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)));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow