2

Consider this code:

 var files = Directory.GetFiles(filePath);
 var dataFiles = from file in files
                 where System.IO.Path.GetExtension(file) == extension 
                 orderby file.Length
                 select file;

I've been looking for a string comparator that will do "natural sort". Sadly, there is no build-in functionality for this common task. I found this post and it looks good.

Can I use NaturalStringComparer with LINQ query syntax? I am aware of the solution with lambdas.

Community
  • 1
  • 1
Lukasz Madon
  • 14,664
  • 14
  • 64
  • 108

3 Answers3

5

Unfortunately this is not possible since the overload of OrderBy with a custom comparer is not supported in query syntax - only method syntax makes it accessible:

var comparer = new NaturalStringComparer();
var dataFiles = files.Where(f => System.IO.Path.GetExtension(f) == extension)
                     .OrderBy(f => f, comparer);
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
1

You need to use the extension method syntax:

files.OrderBy(file => file.Length, new NaturalStringComparer())
usr
  • 168,620
  • 35
  • 240
  • 369
1
        var files = Directory.GetFiles("C:\\");
        var dataFiles = from file in files
                        where System.IO.Path.GetExtension(file) == extension
                        orderby file
                        select file;

this might help you.

VIJAYBEDRE
  • 11
  • 2