LINQ 全称是 Language Integrated Query.
LINQ适合于任何实现了IEnumerable<T>的任何对象。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);
}
}
}
}