摘要:透過LINQ篩選目錄中的檔案,用GridView顯示篩選結果
LINQ to Object真是好用,只要能夠把資料放到【物件集合】後,接下來要去下條件篩選,對LINQ來說是輕而易舉的事情。
這裡就用檔案系統來做個範例
再以下這篇中,已經提到怎麼用GridView來顯示某資料夾裡面的內容
http://www.dotblogs.com.tw/topcat/archive/2008/03/06/1278.aspx
這裡更將這個應用衍生用LINQ來篩選,我們將會作以下這些事情
- 依照指定的資料夾,撈出資料夾中的檔案資訊,放到ViewState中
- 透過LINQ撈取指定的副檔名檔案,並顯示在GridView中
作法如下:
首先一樣的安排一下畫面的控制項:
資料夾:<asp:TextBox ID="txtDir" runat="server"></asp:TextBox> <asp:Button ID="btnGetAllData" runat="server" Text="讀取資料夾檔案" /> <br /> <div id="divC" runat="server"> 附檔名: <asp:TextBox ID="txtCData" runat="server"></asp:TextBox> <asp:Button ID="btnQry2" runat="server" Text="篩選" /> </div> <br /> <asp:GridView ID="GridView1" runat="server"> </asp:GridView> |
接著在CodeFile中的程式,先處理會用到的Imports,這邊等下會用到LINQ,不要忘了這個重要的System.Linq



再來宣告一個變數用來存放資料夾中的檔案資訊

在PageLoad的時候,先從ViewState中取回myFiles,如果一開始沒有東西,就New一下產生執行個體






接著處理取得資料夾內所有檔案資訊並放入myFiles中







從最後的部分,使用LINQ來篩選資料真是輕鬆愉快啊,只要設定好Where的條件就可以了^_^
以下是簽名:
- 歡迎轉貼本站的文章,不過請在貼文主旨上加上【轉貼】,並在文章中附上本篇的超連結與站名【topcat姍舞之間的極度凝聚】,感恩大家的配合。
- 小喵大部分的文章會以小喵熟悉的語言VB.NET撰寫,如果您需要C#的Code,也許您可以試著用線上的工具進行轉換,這裡提供幾個參考
Microsoft MVP Visual Studio and Development Technologies (2005~2019/6) | topcat Blog:http://www.dotblogs.com.tw/topcat |