如何对段落列表进行排序

发布于 2024-10-08 14:38:36 字数 338 浏览 0 评论 0原文

A 有一个列表:
§ 21 项
§ 1 项
§ 13 项目
§ 3 项
§ 2 项目

我需要这样订购:
§ 1 项
§ 2 项目
§ 3 项
§ 13 项目
§ 21 项目

但是在

newList = (from a in list orderby a.Name ascending select a).ToList();  

我得到这个之后:
§ 1 项
§ 13 项目
§ 2 项目
§ 21 项
§ 3 项目

如何解决?

A have a list:
§ 21 Item
§ 1 Item
§ 13 Item
§ 3 Item
§ 2 Item

I need to order it like this:
§ 1 Item
§ 2 Item
§ 3 Item
§ 13 Item
§ 21 Item

But after

newList = (from a in list orderby a.Name ascending select a).ToList();  

I get this:
§ 1 Item
§ 13 Item
§ 2 Item
§ 21 Item
§ 3 Item

How to fix it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

和我恋爱吧 2024-10-15 14:38:36

您正在寻找的是自然排序而不是默认的词法排序。实现自然排序的 C# 比较器可以在 http://www.davekoelle.com/alphanum.html< 找到/a>

What you are looking for is a natural sort rather than the default lexical sort. A C# comparer that implements natural sort can be found at http://www.davekoelle.com/alphanum.html

酒中人 2024-10-15 14:38:36
... orderby int.Parse(a.Name.Split(" ")[1]) ...
... orderby int.Parse(a.Name.Split(" ")[1]) ...
小霸王臭丫头 2024-10-15 14:38:36

谷歌有答案:获取Linq to OrderBy 以数字表示的属性值

from a in list
orderby int.Parse(a.Name)
select ...

Google has the answer: Getting Linq to OrderBy an attribute value numerically.

from a in list
orderby int.Parse(a.Name)
select ...
仙气飘飘 2024-10-15 14:38:36

011 不同。按字典顺序,13 位于 3 之前。假设所有“段落”都以非零前缀整数开头,您将需要解析每个整数并按该整数对列表进行排序。

如果列表项没有以整数为前缀,前面的答案将抛出FormatException

01 is different from 1. Lexicographically 13 comes before 3. Presuming that all "paragraphs" are prepended with a non-zero-prefixed integer, you will need to parse each integer and order your list by that.

The previous answers will throw FormatException if a list item is not prefixed by an integer.

一身软味 2024-10-15 14:38:36

这应该有效:

var list = new List<string> {"§ 21 Item", "§ 1 Item", "§ 13 Item", "§ 3 Item", "§ 2 Item"};
var orderedList = (from a in list orderby int.Parse(a.Split(' ')[1]) ascending select a).ToList();

This should work:

var list = new List<string> {"§ 21 Item", "§ 1 Item", "§ 13 Item", "§ 3 Item", "§ 2 Item"};
var orderedList = (from a in list orderby int.Parse(a.Split(' ')[1]) ascending select a).ToList();
韬韬不绝 2024-10-15 14:38:36

容纳空白条目

newList = (from a in list 
           orderby String.IsNullOrEmpty(a) 
                     ? -1 
                     : int.Parse(a.Name.Split(" ")[1]) ascending 
           select a).ToList();  

to accomodate blank entry

newList = (from a in list 
           orderby String.IsNullOrEmpty(a) 
                     ? -1 
                     : int.Parse(a.Name.Split(" ")[1]) ascending 
           select a).ToList();  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文