LINQ学習ノート(01)


LINQのフルネームはLanguage Integrated Query.
LINQはIEnumerableを実装した任意のオブジェクトに適している.C#3.0 LINQのサポートを開始LINQは、例えば、以下のような複数の態様に適用することができる.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace LINQForFIles
{
    class Program
    {
        static IEnumerable<string> GetAllFilesInDirectory(string directoryPath)
        {
            return Directory.EnumerateFiles(directoryPath, "*", SearchOption.TopDirectoryOnly);
        }
        static void Main(string[] args)
        {
            DoNothingInSelect();
            DoSomethingInSelect();
        }

        static void DoNothingInSelect()
        {
            var bigFiles = from file in GetAllFilesInDirectory("d:\\")
                           where new FileInfo(file).Length > 100000000
                           select file;

            foreach (string file in bigFiles)
            {
                Console.WriteLine(file);
            }

            var anotherWayForBigFiles = GetAllFilesInDirectory("d:\\").Where(file => new FileInfo(file).Length > 100000000);
            foreach (string file in anotherWayForBigFiles)
            {
                Console.WriteLine(file);
            }
        }

        static void DoSomethingInSelect()
        {
            var bigFiles = from file in GetAllFilesInDirectory(@"d:\")
                           where new FileInfo(file).Length > 100000000
                           select "File Name: " + file;
            foreach (string file in bigFiles)
            {
                Console.WriteLine(file);
            }

            var anotherWayForBigFiles = GetAllFilesInDirectory(@"d:\").Where(file => new FileInfo(file).Length > 100000000).Select(file => "FileName: " + file);
            foreach (string file in anotherWayForBigFiles)
            {
                Console.WriteLine(file);
            }
        }
    }
}