dtjmsy
dtjmsy

Reputation: 2752

Files in directory sort by fileName ascending

I am having a list of files from a directory and I want to sort it out by filename.

This is the main code:

var localPath = this.Server.MapPath("~/Content/Img/" + type + "/");
var directory = new DirectoryInfo(localPath);
isDirectory = directory.Exists;

if (isDirectory)
{
    foreach (FileInfo f in directory.GetFiles())
    {
        Picture picture = new Picture();

        picture.ImagePath = path;
        picture.CreationDate = f.CreationTime;
        picture.FileName = f.Name;
        listPictures.Add(picture);
    }
}

here is the class Picture where all the files are stored:

public class Picture
{
    public string ImagePath { get; set; }
    public string FileName { get; set; }
    public DateTime CreationDate { get; set; }
}

How do you do to sort a files list by order of FileName?

Upvotes: 3

Views: 22721

Answers (5)

Tim Schmelter
Tim Schmelter

Reputation: 460018

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.

Upvotes: 1

abatishchev
abatishchev

Reputation: 100238

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

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

Upvotes: 1

Adil
Adil

Reputation: 3268

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

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

Upvotes: 2

Steve B
Steve B

Reputation: 37660

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

Upvotes: 9

Maarten
Maarten

Reputation: 22945

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

Upvotes: 2

Related Questions