开发者

How to sort in a linq query?

开发者 https://www.devze.com 2023-01-27 16:29 出处:网络
So I am getting some files like this: int pathLength = path.Length + 1; var files = Directory.GetFiles ( path, \"*.*\", SearchOption.AllDir开发者_如何学运维ectories )

So I am getting some files like this:

int pathLength = path.Length + 1;
var files = Directory.GetFiles ( path, "*.*", SearchOption.AllDir开发者_如何学运维ectories )
    .Where ( s => s.EndsWith ( ".bmp", StringComparison.OrdinalIgnoreCase ) ||
        s.EndsWith ( ".jpg", StringComparison.OrdinalIgnoreCase ) )
        .Select ( s => s.Substring ( pathLength, s.Length - pathLength ) )

    .ToList ( );

and was before sorting like this:

FileComparer fileComparer = new FileComparer ( );
files.Sort ( fileComparer );

But for Sort I need to use ToList. I am wondering if I can just add the Sort to the Linq the same way and get rid of ToList?


You're looking for the OrderBy method:

var extensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".bmp", ".jpg" };
int pathLength = path.Length + 1;
var files = Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories)
    .Where(s => extensions.Contains(Path.GetExtension(s)))
    .Select(s => s.Substring(pathLength))
    .OrderBy(s => s, new FileComparer());

You can replace your FileComparer class with

.OrderBy(s => !s.Contains('\\')).ThenBy(s => s)

Since false < true, this will sort strings that start with \\ before other ones.


Use OrderBy method.

Your code will change from -

files.Sort((x, y) => string.Compare(x.fileName, y.fileName));

to -

files.OrderBy(x => x.fileName);

Update

files.OrderBy(x => x.fileName.Contains(@"\\")).ThenBy(x => x.fileName);


.OrderBy(f => f, new FileComparer())

(this assumes FileComparer implements IComparer<string>)


There's a few things you can do to improve your code :

  • like said previously, use OrderBy for sort

  • write your request as a LINQ expression rather than successive method calls :

    var files = (from file in Directory.GetFiles ( path, "*.*", SearchOption.AllDirectories )
                where file.EndsWith ( ".bmp", StringComparison.OrdinalIgnoreCase ) ||
                 file.EndsWith ( ".jpg", StringComparison.OrdinalIgnoreCase )
                 orderby new FileComparer()
                 select file);
    

    The code above does the same than yours but is more elegant.

  • To get path, extension, file name... I strongly recommend you to use System.IO.Path helpers methods rather than perform string operations like substring or contains !!

  • Rather than use Directory.GetFiles you could instantiate a DirectoryInfo and call the GetFiles method : this one has the advantage to return an array of FileInfo, which exposes directly properties like extension, file name...

Hope this helps

0

精彩评论

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