How can I do numerical sorting using strings?

I have a list of items that I call.

Each page element has the following meanings:

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

The problem is that the file name fields are arranged as follows:

1.tif
10.tif

and I need them to be ordered in a list:

1.tif
2.tif

I tried the following with no luck:

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

Thank!

+3
source share
5 answers

According to your example, you need something like this:

pageList.Sort((a, b) => Int32.Parse(a.ImageName.Replace(".tif", "")).CompareTo(Int32.Parse(b.ImageName.Replace(".tif","")))
+2
source
using System.Linq; // System.Core.dll

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

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

If you are looking for a sort order that is sensitive to both alphabetical and numerical order, such as found in Windows Explorer, this is called "Natural Sort Order".

The following question and answer will help:

Natural sort order in C #

+1
source

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

Gives you a list sorted by extension and then by file name.

0
source

All Articles