Searching files with LINQ

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();
    }

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();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: