Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following code

DirectoryInfo taskDirectory = new DirectoryInfo(this.taskDirectoryPath);
FileInfo[] taskFiles = taskDirectory.GetFiles("*" + blah + "*.xml");

I would like to sort the list by filename.

How is this done, as quickly and easily as possible using .net v2.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
474 views
Welcome To Ask or Share your Answers For Others

1 Answer

Call Array.Sort, passing in a comparison delegate:

Array.Sort(taskFiles, delegate(FileInfo f1, FileInfo f2) {
    return f1.Name.CompareTo(f2.Name);
});

In C# 3 this becomes slightly simpler:

Array.Sort(taskFiles, (f1, f2) => f1.Name.CompareTo(f2.Name));

Or you can use a StringComparer if you want to use a case-insensitive sort order:

Array.Sort(taskFiles,
           (x, y) => StringComparer.OrdinalIgnoreCase.Compare(x.Name, y.Name));

(or use string.Compare(x.Name, y.Name, true), or any of the many other ways of comparing strings :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...