Archive for the ‘LINQ’ Category

Linqでファイルを作成日順でソート

2009年1月5日

MSDNのサンプルそのままだけど、ちょっと便利。
       private void Form1_Load(object sender, EventArgs e)
        {
            string startFolder = @"C:\My Documents\My Pictures\";

            // Take a snapshot of the file system.
            IEnumerable fileList = GetFiles(startFolder);

            //Create the query
            IEnumerable fileQuery =
                from file in fileList
                where file.Extension == ".jpg"
                orderby file.Name
                select file;

            // Create and execute a new query by using the previous
            // query as a starting point. fileQuery is not
            // executed again until the call to Last()
            var files =
                (from file in fileQuery
                 orderby file.CreationTime
                 select new { file.FullName, file.CreationTime });
        }

        // This method assumes that the application has discovery
        // permissions for all folders under the specified path.
        static IEnumerable GetFiles(string path)
        {
            if (!System.IO.Directory.Exists(path))
                throw new System.IO.DirectoryNotFoundException();

            string[] fileNames = null;
            List files = new List();

            fileNames = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
            foreach (string name in fileNames)
            {
                files.Add(new FileInfo(name));
            }
            return files;
        }
広告