LINQ and a natural sort order [duplicate]

青春壹個敷衍的年華 提交于 2019-12-17 18:38:43

问题


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;

回答1:


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.




回答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)));


来源:https://stackoverflow.com/questions/1323550/linq-and-a-natural-sort-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!