开发者

How can I perform a numerically-valid sort using strings?

I have a List of items I call pages.

Each page items has the following:

int id { get; set; }
string filename { get; set; }
int status  { get; set; }

The problem I have is that the filename fields are ordered like this:

1.tif
10.tif

and I need them ordered in the list like this:

1.tif
2.tif

I tried the following wi开发者_高级运维thout luck:

pageList.Sort((a, b) => String.Compare(a.ImageName, b.ImageName));

Thanks!


Going strictly by your example, you need something like this:

pageList.Sort((a, b) => Int32.Parse(a.ImageName.Replace(".tif", "")).CompareTo(Int32.Parse(b.ImageName.Replace(".tif","")))


If I understand your question right, you want to sort "numeric" filenames in natural numeric order.

This article might give you some pointers: http://www.codeproject.com/KB/recipes/csnsort.aspx


using System.Linq; // System.Core.dll

IEnumerable<Page> sequence = pageList.OrderBy(x => x.ImageName); // not in-place sort

List<Page> list = sequence.ToList();


If you're looking for a sort order that is sensitive to both alphabetic and numerical order such as that found in Windows Explorer, this is referred to as a "Natural Sort Order".

The following question and answer will be of help:

Natural Sort Order in C#


I believe:

pageList = pageList.GroupBy(p => p.filename.Substring(p.filename.IndexOf('.') + 1)).
    OrderBy(g => g.Key).SelectMany(g => g.OrderBy(p => p.filename)).ToList();

Would give you the list ordered by extension and then by filename.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜