本博文接着上幾篇LINQ to Object和多線程的相關博文,用LINQ to Object和多線程實現文件查找與分組的Demo作為LINQ to Object 的一個小結。
程序的功能如下:點擊界面右上角按鈕選擇一個文件夾,多線程加載文件,LINQ進行相關的查詢,實現分組查找等功能。
程序的注釋中,DebugLZQ加入了很詳細的注釋,以及,LZ代碼寫作的流程,因此這里不做更多的介紹,LINQ和多線程的相關技能請參考DebugLZQ前面的幾篇博文。
代碼如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; using System.IO; /// ///DebugLZQ ///http://www.cnblogs.com/DebugLZQ ///LINQ to Object & 線程操作 namespace 文件查找與分組 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private string filePath = ""; ///////////////////////////////////////////// //a4 //得到選定目錄下的文件類型 private string[] GetFileTypes() { string[] files = Directory.GetFiles(filePath, "*.*", SearchOption.AllDirectories);//獲得目錄下所有的文件 //LINQ獲得文件分組 var filesLookup = files.ToLookup(f=>f.Substring(f.LastIndexOf('.')).ToUpper()); //從分組中獲得Key(即文件類型),並排序 var fileTypes = from t in filesLookup orderby t.Key select t.Key; return fileTypes.ToArray(); } // //b6 //根據指定類型獲得文件名 private string[] GetFilesByType(string type) { string[] files = Directory.GetFiles(filePath, "*.*", SearchOption.AllDirectories);//獲得目錄下所有的文件 var filesByType = from f in files where f.Contains(type.ToLower())||f.Contains(type) select f; return filesByType.ToArray(); } // //c8 //查找文件 private string[] FindFile(string str) { string[] files = Directory.GetFiles(filePath, "*.*", SearchOption.AllDirectories);//獲得目錄下所有的文件 var filesTake = from f in files where f.Contains(str) select f; return filesTake.ToArray(); } //////////////////////////////////////////// //a2 //訪問磁盤,讀取文件 private void LoadFile() { Thread t = new Thread(new ThreadStart(loadfile)); t.Start(); } private delegate void loadfileDelegate(); //a3 private void loadfile() { if (this.InvokeRequired == true)//注意這里 { loadfileDelegate lfd = new loadfileDelegate(loadfile); this.Invoke(lfd); return; } //獲得文件類型 string[] fileTypes = GetFileTypes(); //Binding fileTypeLst.DataSource = fileTypes; } //a1 private void btnSelDir_Click(object sender, EventArgs e) { if (folderBrowserDialog1.ShowDialog()== System.Windows.Forms.DialogResult.OK ) { filePath = folderBrowserDialog1.SelectedPath; txtFolder.Text = folderBrowserDialog1.SelectedPath; LoadFile(); } } //b5 private void fileTypeLst_SelectedIndexChanged(object sender, EventArgs e) { //根據文件類型獲得文件名 string[] files = GetFilesByType(fileTypeLst.SelectedItem.ToString()); //Binding fileLst.DataSource = files; } //c7 private void txtFind_TextChanged(object sender, EventArgs e) { if (txtFind.Text.Length == 0) { return; } string[] files = FindFile(txtFind.Text); //Binding fileLst.DataSource = files; } } }
程序的界面,及運行結果如下: