Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

c# - How to sort an array of FileInfo[]

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...