开发者

How to order a list of paragraphs

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

开发者_如何学PythonnewList = (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?


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


... orderby int.Parse(a.Name.Split(" ")[1]) ...


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

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


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.


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();


to accomodate blank entry

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜