簡體   English   中英

使用LINQ動態查詢文件系統信息

[英]Query File System Info Dynamically using LINQ

我需要能夠返回符合某些動態條件的文件列表。 我試過用LINQ做這個。

我發現使用Scott Gu的博客中提到的System.Linq.Dynamic命名空間可以使用動態LINQ。

但我不確定是否可以用於我需要的東西。

到目前為止,我得到了所有的文件,但我不知道從那里去哪里。

// Take a snapshot of the file system.
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(SourceLocation);

// This method assumes that the application has discovery permissions
// for all folders under the specified path.
IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles("*.*", System.IO.SearchOption.AllDirectories);

我現在需要能夠使用用戶創建的一些動態過濾器來過濾這些文件。 例如Extension = .txt

誰能指出我正確的方向?

謝謝。 馬丁。

編輯:

Dynamic Linq庫中的示例如下所示:

var query =
            db.Customers.Where("City == @0 and Orders.Count >= @1", "London", 10).
            OrderBy("CompanyName").
            Select("New(CompanyName as Name, Phone)");

我希望能夠適應文件系統。 所以我可以建立一個過濾字符串並使用它。

這是我用過的方法。

var diSource = new DirectoryInfo(SourceLocation);            
var files = GetFilesRecursive(diSource);
var matches = files.AsQueryable().Where(sFilter, oParams);

SourceLocation只是我想要搜索的目錄的文件路徑。 GetFileRecursive只是一個自定義方法,用於返回子文件夾中的所有文件。

我根據用戶定義的過濾器構建了sFilter參數,oParams是這些過濾器的值數組。 這允許我的用戶根據需要動態定義盡可能多的過濾器。

var files = fileList.Where(
    f => f.Modified > DateAdd(DateInterval.Days, -1, DateTime.Now);

要么

var files = fileList.Where(f => f.Name.EndsWith(".txt"));

要么

var files = fileList.Where(f => f.IsReadOnly);

這是LINQ。 f => f. part,您可以將任何求值的表達式放到布爾值中。 天空是極限。 您可以編寫一個接受FileInfo對象的函數,讀取文件的文本,如果它包含特定的短語,則返回true。 然后你會這樣做......

var files = fileList.Where(f => MyFunction(f));

關於用戶創建的過濾器,你真的必須設計一個適合可能情況的UI和后端。

除非您使用fileinfo屬性作為過濾的一部分,否則您只需使用以下內容:

IEnumerable<System.IO.FileInfo> fileList = dir.GetFiles(**"*.txt"**,
 System.IO.SearchOption.AllDirectories);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM