-1

I have files in my folder with names like these:

"C:\\Users\\John\\Documents\\333\\12.html"

How to sort them so that 2.html will come before 10.html?

Dor Cohen
  • 16,769
  • 23
  • 93
  • 161
user1322207
  • 289
  • 3
  • 7
  • 14

3 Answers3

4

Parse the strings as numbers when you sort the files.

Example:

string[] files = {
  "2.html",
  "10.html",
  "1.html"
};

files =
  files.OrderBy(s => Int32.Parse(s.Substring(0, s.IndexOf('.'))))
  .ToArray();
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • And then it will fail on "Part 1.html", "a.html" and "b.html". Your solution will only work in the specific case of file names looking like `.`. – penartur Apr 19 '12 at 12:39
  • @penartur : conform the specs. Read the question. – H H Apr 19 '12 at 12:40
  • The question says "file names are **like** `3.html`", not "file names are exactly `.`". In the context of question, `part 3.html` is like `3.html`. – penartur Apr 20 '12 at 08:05
  • @penartur: The example shows what kind of strings it works with. Whatever anyone may think about what the question means, the answer in itself defines what question it is answering. – Guffa Apr 20 '12 at 08:39
2
    Directory
      .GetFiles()
      .OrderBy(f => int.Parse(Path.GetFileNameWithoutExtension(f)) )
H H
  • 263,252
  • 30
  • 330
  • 514
1

Look at this post -

http://www.codeproject.com/Articles/11016/Numeric-String-Sort-in-C

string[] files = System.IO.Directory.GetFiles();

NumericComparer ns = new NumericComparer();
Array.Sort(files, ns);

// files will now sorted in the numeric order
// we can do the same for directories

string[] dirs = System.IO.Directory.GetDirectories();
ns = new NumericComparer(); // new object
Array.Sort(dirs, ns);

public class NumericComparer : IComparer
    {
        public NumericComparer()
        {}

        public int Compare(object x, object y)
        {
            if((x is string) && (y is string))
            {
                return StringLogicalComparer.Compare((string)x, (string)y);
            }
            return -1;
        }
    }//EOC
Dor Cohen
  • 16,769
  • 23
  • 93
  • 161