Shane Grant
Shane Grant

Reputation: 2654

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 without luck:

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

Thanks!

Upvotes: 3

Views: 391

Answers (5)

Tim Lloyd
Tim Lloyd

Reputation: 38494

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#

Upvotes: 1

abatishchev
abatishchev

Reputation: 100358

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

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

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

Upvotes: 1

FlyingStreudel
FlyingStreudel

Reputation: 4464

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.

Upvotes: 0

to StackOverflow
to StackOverflow

Reputation: 124794

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

Upvotes: 1

Matt Hamsmith
Matt Hamsmith

Reputation: 4036

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","")))

Upvotes: 2

Related Questions