Filter the file list with a query - CSharp LINQ

CSharp examples for LINQ:where

Description

Filter the file list with a query

Demo Code



using System;//from w  w  w.  j  av a 2  s .c  o  m
using System.Collections.Generic;
using System.Linq;
using System.IO;
class Program
{
    static void Main(string[] args)
    {
        Environment.CurrentDirectory = @"c:/a";
        string path = Environment.CurrentDirectory;
        DirectoryInfo di = new DirectoryInfo(path); // Where path is the directory path.
        FileInfo[] files = di.GetFiles();

        Console.WriteLine("\tFilter the file list the old-fashioned way:");

        foreach (FileInfo file in files)
        {
            if (file.Extension.ToLower() == ".txt")
            {
                Console.WriteLine("\t\t{0}", file.Name);
            }
        }
        Console.WriteLine("\tFilter the file list with a query:");
        var justTextFiles = from f in files
                            where f.Extension.ToLower() == ".txt"
                            select f;
        foreach (var file in justTextFiles)
        {
            Console.WriteLine("\t\t{0}", file.Name);
        }
    }
}

Result


Related Tutorials