[英]How can i sort the directories as they appear on my hard disk?
例如,在我的硬盤上:
dir1 dir2 dir3 dir4 .....
我的代碼是:
DirectoryInfo dInfo = new DirectoryInfo(AutomaticsubDirectoryName);
DirectoryInfo[] subdirs = dInfo.GetDirectories();
所以在subdirs
我得到了所有目錄,但它們的順序與我的硬盤上的順序不同。 我如何對它們進行排序,以便它們以與硬盤上相同的順序位於subdirs
中?
解決此問題:
DirectoryInfo[] subdirs = dInfo.GetDirectories().OrderBy(d =>
{
int i = 0;
if (d.Name.Contains("Lightning ") && d.Name.Contains(" Length") && d.Name.IndexOf("Lightning ") < d.Name.IndexOf(" Length"))
{
string z = d.Name.Substring(("Lightning ").Length);
string f = z.Substring(0, z.IndexOf(" Length"));
if (Int32.TryParse(f, out i))
return i;
else
return -1;
}
else
return -1;
}).ToArray();
工作完美。
假設您正在談論文件系統以及Windows Explorer之類的軟件如何顯示名稱,我想您正在談論對名稱進行自然排序。 在這里閱讀: http : //www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html
Craetion time
是合理的標准,它們如何出現在硬盤上。
DirectoryInfo[] subdirs = dInfo.GetDirectories().OrderBy(d => d.CreationTime).ToArray();
Windows使用的字符串比較功能可供所有人使用。 因此,您將需要一點點拼音才能獲得與資源管理器使用的排序順序完全相同的排序順序。 將其包裝在IComparer <>中,因此您可以將其傳遞給Array.Sort()或OrderBy()Linq子句:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
public class LogicalComparer : IComparer<string> {
public int Compare(string x, string y) {
return StrCmpLogicalW(x, y);
}
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
private static extern int StrCmpLogicalW(string s1, string s2);
}
解決此問題:
DirectoryInfo[] subdirs = dInfo.GetDirectories().OrderBy(d =>
{
int i = 0;
if (d.Name.Contains("Lightning ") && d.Name.Contains(" Length") && d.Name.IndexOf("Lightning ") < d.Name.IndexOf(" Length"))
{
string z = d.Name.Substring(("Lightning ").Length);
string f = z.Substring(0, z.IndexOf(" Length"));
if (Int32.TryParse(f, out i))
return i;
else
return -1;
}
else
return -1;
}).ToArray();
工作完美。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.