LINQ is very powerful in many aspects of programming; for example, you can simulate the search for files feature of some known applications (Windows Explorer or Total Commander) with very few lines of code, as shown below:
public List<FileInfo> SearchForFiles(String path, String ext, String search)
{
DirectoryInfo folder = new DirectoryInfo(path);
return (from file in folder.GetFiles(ext, SearchOption.AllDirectories)
where file.Name.ToLower().Contains(search.ToLower())
orderby file.Name, file.Extension
select file).ToList();
}
{
DirectoryInfo folder = new DirectoryInfo(path);
return (from file in folder.GetFiles(ext, SearchOption.AllDirectories)
where file.Name.ToLower().Contains(search.ToLower())
orderby file.Name, file.Extension
select file).ToList();
}
Then, you can use in several ways the resulted list, for example by adding to your Windows Form application a DataGridView and setting its DataSource as following:
dgvFiles.DataSource = SearchForFiles(path, extension, searchTerm).ToList();
Advertisement
