问题
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?
回答1:
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);
回答2:
listPictures = listPictures.OrderBy(x => x.FileName).ToList();
回答3:
You can use lambda expression and/or extension methods. For example:
listPictures.OrderBy(p => p.FileName).ToList();
回答4:
Note that EnumerateFiles performs lazy loading and can be more efficient for larger directories, so:
dir.EnumerateFiles().OrderBy(f => f.FileName))
回答5:
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.
来源:https://stackoverflow.com/questions/12155131/files-in-directory-sort-by-filename-ascending