2 回答

TA貢獻1848條經驗 獲得超10個贊
把它當作
PropertyInfo propertyInfo = typeof(FileInfo).GetProperty(orderByParam);
var files = Directory
.EnumerateFiles(strPath)
.OrderBy(f => propertyInfo.GetValue(new FileInfo(f), null));
f由于您希望從(new FileInfo(f)準確地說)讀取屬性值,所以不orderByParam

TA貢獻1906條經驗 獲得超10個贊
問題是您沒有在 OrderBy 中使用參數 f
.OrderBy(f => propertyInfo.GetValue(orderByParam, null));
你讓事情變得比需要的更復雜。
要求:給定一個目錄的名稱,以及類 FileInfo 的屬性之一的名稱,給我這個目錄中由這個屬性排序的所有文件的順序。
我的建議是不要為此使用反射,而是為您的訂購創建一個 IComparer 類。
這有幾個優點。反射相當緩慢。比較器也可以用于 OrderByDescending。但最重要的優勢是您可以控制要訂購的 PropertyNames。
您可以拒絕按屬性訂購,也可以按屬性拒絕Directory訂購Exists。除了通過“長度”添加對訂單的支持之外,您還可以通過“長度”/“長度”/“長度”添加對訂單的支持。如果需要支持命令行輸入,可以通過“-l”/“-L”添加對命令的支持
如果您創建一個比較器類,用法將是:
string directoryName = ...
// TODO: exception if directoryName null or empty
DirectoryInfo directory = new DirectoryInfo(directoryName);
if (!directory.Exists) TODO: exception
IComparer<FileInfo> comparer = ...
IEnumerable<FileInfo> files = directory.EnumerateFiles();
IEnumerable<FileInfo> orderedFiles = files.OrderBy(file => file, comparer);
IComparer 的實現相當簡單:
class FileInfoComparer<TKey> : IComparer<FileInfo>
{
public static IComparer<FileInfo> Create(string propertyName)
{
// this Compare supports only property names of FileInfo
// and maybe not even all property names
switch (propertyName)
{
case "Name":
return new FileInfoComparer(fileInfo => fileInfo.Name);
case "Length":
return new FileInfoComparer(fileInfo => fileInfo.Length);
case "Extension"
return new FileInfoComparer(fileInfo => fileInfo.Extension);
...
default:
throw new NotSupportedException("Ordering by this property not supported");
// for instance: property names "Directory" "Exists"
}
}
private FileInfoComparer(Func<FileInfo, TKey> keySelector)
{
this.keySelector = keySelector;
}
private readonly Func<FileInfo, TKey> keySelector;
private readonly IComparer<TKey> keyComparer = Comparer<TKey>.Default;
public int Compare(FileInfo x, FileInfo y)
{
// TODO: decide what to do if x or y null. Exception? first or last in sort order?
return keyComparer.Compare(this.keySelector(x), this.keySelector(y));
}
}
我創建了一個私有構造函數,所以只有 Create 函數可以創建這個比較器。
用法:
var comparer = FileInfoComparer.Create("Length"); DirectoryInfo 目錄 = 新 DirectoryInfo(directoryPath); var orderedFiles = directory.EnumerateFiles.Orderby(file => file, comparer);
- 2 回答
- 0 關注
- 168 瀏覽
添加回答
舉報