score:9

Accepted answer

Simply change your for loop :

foreach (FileInfo f in directory.GetFiles().OrderBy(fi=>fi.FileName))
{

}

Alternatively, you can rewrite the whole loop using this code :

var sortedFiles = from fi in directory.GetFiles()
                  order by fi.FileName
                  select new Picture { ImagePath = path, CreationDate = f.CreationTime, FileName = f.FileName };

listPictures.AddRange(sortedFiles);

score:2

listPictures = listPictures.OrderBy(x => x.FileName).ToList();

score:2

You can use lambda expression and/or extension methods. For example:

listPictures.OrderBy(p => p.FileName).ToList();

score:1

Note that EnumerateFiles performs lazy loading and can be more efficient for larger directories, so:

dir.EnumerateFiles().OrderBy(f => f.FileName))

score:1

You can use LINQ from the beginning:

var files = from f in directory.EnumerateFiles()
    let pic = new Picture(){
        ImagePath = path;
        CreationDate = f.CreationTime;
        FileName = f.Name;
    }
    orderby pic.FileName
    select pic;

Note that Directory.EnumerateFiles(path) will be more efficient if only the FileName is used.


Related Articles