LINQ 概述、语法及实例

概述

These seven foundational principles state that LINQ is:

Ø Integrated: LINQ is a first-class citizen of .NET languages such as C# and VB and as such is fully type-checked. Inside Visual Studio it is syntax-highlighted and IntelliSense-aware.

Ø Unitive: LINQ provides a single syntax for querying multiple data sources, including relational data found in a SQL database, XML data, and the objects in a program.

Ø Extensible: LINQ can be adapted to work with multiple languages and to query multiple data sources. LINQ to XML, LINQ to SQL, and LINQ to Objects are only three possible forms of LINQ. Developers can extend the language to query almost any arbitrary data source, such as a file system, web service, or network protocol.

Ø Declarative: A LINQ developer tells the compiler what to do, without focusing on how to perform a task or in what order tasks must be performed.

Ø Hierarchical: LINQ provides a rich, object-oriented view of data. A more rigorous or mathematical view of this same theme would focus on LINQ’s capability to generate and manipulate graphs.

Ø Composable: The results of one query can be used by a second query, and one query can be a subclause of another query. In many cases, this can be done without forcing the execution of any one query until the developer wants that execution to take place. Thus, you can write three separate but related queries. LINQ automatically notes the connections between them and combines them into a single, efficient query that executes only once. This allows you to “divide and conquer” by breaking up the logic of your query just as you divide the logic of your program across multiple classes and methods.

Ø Transformative: The results of a LINQ query against one data source can be transformed into a second data source. For instance, a query against a SQL database can produce an XML file as output.

[Essential LINQ ISBN:978-0-321-56416-0 第3章对这些特性有详细描述]

语法

语言扩展

为了支持Linq,扩展的语言特性如下:

隐式局部变量
对象和结合初始化器
扩展方法
Lambda表达式

ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.chs/dv_csref/html/57e3ba27-9a82-4067-aca7-5ca446b7bf93.htm

“Lambda 表达式”是一个匿名函数,它可以包含表达式和语句,并且可用于创建委托或表达式目录树类型。

表达式在右边的 Lambda 表达式称为“Lambda 表达式”。 Lambda 表达式在构造表达式目录树时广泛使用。Lambda 表达式返回表达式的结果,并采用以下基本形式:

(input parameters) => expression

Lambda 语句与 Lambda 表达式类似,只是语句括在大括号中:

(input parameters) => {statement;}

Func<(Of <(T, TResult>)>)

匿名类型
以上扩展特性的例子

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
internal static class ProcessExtension
{
public static long TotalMemory(this IEnumerable<ProcessData> processes)
{
// 扩展方法 extension methods
long result = 0;
foreach (var process in processes)
{
result += process.Memory;
}
return result;
}
}
internal class ProcessData
{
public int Id { get; set; }
public long Memory { get; set; }
public string Name { get; set; }
}
internal class Syntax
{
public void Run()
{
// lambda expressions
DisplayProcesses(process => process.WorkingSet64 >= 20 * 1024 * 1024);
var list = GetSequence();
var query = from num in list
where num < 3
select num;
// 延迟执行
foreach (var item in query)
{
Console.WriteLine(item);
}
}
public IEnumerable<int> GetSequence()
{
// 编译器能够自动推测类型
// 使用Reflector可以看到生成的代码情况
var length = 3;
// 编译器生成一个类似状态机的辅助结构,实现MoveNext访问yield return的功能
for (int i = 1; i <= length; i++)
{
yield return i;
}
}
private static void DisplayProcesses(Func<Process, bool> match)
{
// 隐式类型局部变量
var processes = new List<ProcessData>();
foreach (var process in Process.GetProcesses())
{
if (match(process))
{
// 对象和集合初始化器
processes.Add(new ProcessData
{
Id = process.Id,
Name = process.ProcessName,
Memory = process.WorkingSet64
});
}
}
// 扩展方法 extension methods
Console.WriteLine("Total memory: {0} MB", processes.TotalMemory() / 1024 / 1024);
var top2Memory = processes.OrderByDescending(process => process.Memory)
.Take(2)
.Sum(process => process.Memory) / 1024 / 1024;
Console.WriteLine("Memory consumed by the two most hungry processes: {0} MB", top2Memory);
// 匿名类型 anonymous types
var results = new
{
TotalMemory = processes.TotalMemory() / 1024 / 1024,
Top2Memory = top2Memory,
Processes = processes
};

 

理解了上以上的概念后,使用中很有用!

posted @ 2010-11-14 20:48  2012  阅读(1346)  评论(0编辑  收藏  举报