在c#上排序数组中的文件目录

时间:2018-04-09 21:01:27

标签: c# arrays file sorting directory

enter image description here

我不想对文件目录进行排序。我有很多文件指示。喜欢: "C:\Users\user\Desktop\programlama\destin\ankara\c11.txt" "C:\Users\user\Desktop\programlama\destin\ankara\a12.txt" "C:\Users\user\Desktop\programlama\destin\ankara\b11.txt"

但它必须按文件名排序。 我怎么能这样做?

Result i want:
a12 at top b11 in the middle c11 at last.

这里是代码示例。

FolderBrowserDialog fbd = new FolderBrowserDialog();

fbd.ShowDialog();
kaynak = fbd.SelectedPath; 
dnm = Directory.GetFiles(kaynak,ftyp, SearchOption.AllDirectories)
                .Select(Path.GetFileName)
                .ToArray();
dsd = Directory.GetFiles(kaynak, ftyp, SearchOption.AllDirectories);

3 个答案:

答案 0 :(得分:1)

一种简单的方法是使用带有Array.Sort的labmda表达式(请注意我已经改变了一些路径以显示它与排序无关:

var files = new string[]
{
    @"C:\Users\user\Desktop\programlama\destin\ankara\c11.txt",
    @"C:\Users\user\Desktop\programlama\destin\a12.txt",
    @"C:\Users\user\Desktop\programlama\ankara\b11.txt"
};


Array.Sort(files, (s1, s2) => Path.GetFileName(s1).CompareTo(Path.GetFileName(s2)));

结果:

C:\Users\user\Desktop\programlama\destin\a12.txt
C:\Users\user\Desktop\programlama\ankara\b11.txt
C:\Users\user\Desktop\programlama\destin\ankara\c11.txt

You can see a live demo on rextester.

答案 1 :(得分:0)

或者您可以使用Linq按路径排序:

var files = new List<string>
{
   @"C:\Users\user\Desktop\programlama\destin\ankara\c11.txt",
   @"C:\Users\user\Desktop\programlama\destin\ankara\a12.txt",
   @"C:\Users\user\Desktop\programlama\destin\ankara\b11.txt"
};

files = files.OrderBy(f => f).ToList();

结果

C:\Users\user\Desktop\programlama\destin\ankara\a12.txt
C:\Users\user\Desktop\programlama\destin\ankara\b11.txt
C:\Users\user\Desktop\programlama\destin\ankara\c11.txt

答案 2 :(得分:-1)

类似的东西:

filesArray.Select(q=> new { FullPath = q, FileName = Path.GetFileName(q)}).OrderBy(q=> q.FileName).Select(q=>q.FullPath);