语言集成查询 (LINQ)Language Integrated Query (LINQ)

语言集成查询 (LINQ) 是一系列直接将查询功能集成到 C# 语言的技术统称。Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. 数据查询历来都表示为简单的字符串,没有编译时类型检查或 IntelliSense 支持。Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support. 此外,需要针对每种类型的数据源了解不同的查询语言:SQL 数据库、XML 文档、各种 Web 服务等。Furthermore, you have to learn a different query language for each type of data source: SQL databases, XML documents, various Web services, and so on. 借助 LINQ,查询成为了最高级的语言构造,就像类、方法和事件一样。With LINQ, a query is a first-class language construct, just like classes, methods, events. 可以使用语言关键字和熟悉的运算符针对强类型化对象集合编写查询。You write queries against strongly typed collections of objects by using language keywords and familiar operators. LINQ 系列技术提供了针对对象 (LINQ to Objects)、关系数据库 (LINQ to SQL) 和 XML (LINQ to XML) 的一致查询体验。The LINQ family of technologies provides a consistent query experience for objects (LINQ to Objects), relational databases (LINQ to SQL), and XML (LINQ to XML).

对于编写查询的开发者来说,LINQ 最明显的“语言集成”部分就是查询表达式。For a developer who writes queries, the most visible "language-integrated" part of LINQ is the query expression. 查询表达式采用声明性查询语法编写而成。Query expressions are written in a declarative query syntax. 使用查询语法,可以用最少的代码对数据源执行筛选、排序和分组操作。By using query syntax, you can perform filtering, ordering, and grouping operations on data sources with a minimum of code. 可使用相同的基本查询表达式模式来查询和转换 SQL 数据库、ADO .NET 数据集、XML 文档和流以及 .NET 集合中的数据。You use the same basic query expression patterns to query and transform data in SQL databases, ADO .NET Datasets, XML documents and streams, and .NET collections.

在 C# 中可为以下对象编写 LINQ 查询:SQL Server 数据库、XML 文档、ADO.NET 数据集以及支持 IEnumerable 或泛型 IEnumerable<T> 接口的任何对象集合。You can write LINQ queries in C# for SQL Server databases, XML documents, ADO.NET Datasets, and any collection of objects that supports IEnumerable or the generic IEnumerable<T> interface. 此外,第三方也为许多 Web 服务和其他数据库实现提供了 LINQ 支持。LINQ support is also provided by third parties for many Web services and other database implementations.

下面的示例展示了完整的查询操作。The following example shows the complete query operation. 完整的操作包括创建数据源、定义查询表达式和在 foreach 语句中执行查询。The complete operation includes creating a data source, defining the query expression, and executing the query in a foreach statement.

class LINQQueryExpressions
    static void Main()
        // Specify the data source.
        int[] scores = new int[] { 97, 92, 81, 60 };

        // Define the query expression.
        IEnumerable<int> scoreQuery =
            from score in scores
            where score > 80
            select score;

        // Execute the query.
        foreach (int i in scoreQuery)
            Console.Write(i + " ");
// Output: 97 92 81

下图为 Visual Studio 中的图例,显示了使用 C# 和 Visual Basic 针对 SQL Server 数据库编写的不完整 LINQ 查询,并具有完全类型检查和 IntelliSense 支持:The following illustration from Visual Studio shows a partially-completed LINQ query against a SQL Server database in both C# and Visual Basic with full type checking and IntelliSense support:

显示具有 Intellisense 的 LINQ 查询的图表。

查询表达式概述Query expression overview

  • 查询表达式可用于查询并转换所有启用了 LINQ 的数据源中的数据。Query expressions can be used to query and to transform data from any LINQ-enabled data source. 例如,通过一个查询即可检索 SQL 数据库中的数据,并生成 XML 流作为输出。For example, a single query can retrieve data from a SQL database, and produce an XML stream as output.

  • 查询表达式易于掌握,因为使用了许多熟悉的 C# 语言构造。Query expressions are easy to master because they use many familiar C# language constructs.

  • 查询表达式中的变量全都是强类型,尽管在许多情况下,无需显式提供类型,因为编译器可以推断出。The variables in a query expression are all strongly typed, although in many cases you do not have to provide the type explicitly because the compiler can infer it. 有关详细信息,请参阅 LINQ 查询操作中的类型关系For more information, see Type relationships in LINQ query operations.

  • 只有在循环访问查询变量后,才会执行查询(例如,在 foreach 语句中)。A query is not executed until you iterate over the query variable, for example, in a foreach statement. 有关详细信息,请参阅 LINQ 查询简介For more information, see Introduction to LINQ queries.

  • 在编译时,查询表达式根据 C# 规范规则转换成标准查询运算符方法调用。At compile time, query expressions are converted to Standard Query Operator method calls according to the rules set forth in the C# specification. 可使用查询语法表示的任何查询都可以使用方法语法进行表示。Any query that can be expressed by using query syntax can also be expressed by using method syntax. 不过,在大多数情况下,查询语法的可读性更高,也更为简洁。However, in most cases query syntax is more readable and concise. 有关详细信息,请参阅 C# 语言规范标准查询运算符概述For more information, see C# language specification and Standard query operators overview.

  • 通常,我们建议在编写 LINQ 查询时尽量使用查询语法,并在必要时尽可能使用方法语法。As a rule when you write LINQ queries, we recommend that you use query syntax whenever possible and method syntax whenever necessary. 这两种不同的形式在语义或性能上毫无差异。There is no semantic or performance difference between the two different forms. 查询表达式通常比使用方法语法编写的等同表达式更具可读性。Query expressions are often more readable than equivalent expressions written in method syntax.

  • 一些查询操作(如 CountMax)没有等效的查询表达式子句,因此必须表示为方法调用。Some query operations, such as Count or Max, have no equivalent query expression clause and must therefore be expressed as a method call. 可以各种方式结合使用方法语法和查询语法。Method syntax can be combined with query syntax in various ways. 有关详细信息,请参阅 LINQ 中的查询语法和方法语法For more information, see Query syntax and method syntax in LINQ.

  • 查询表达式可被编译成表达式树或委托,具体视应用查询的类型而定。Query expressions can be compiled to expression trees or to delegates, depending on the type that the query is applied to. IEnumerable<T> 查询编译为委托。IEnumerable<T> queries are compiled to delegates. IQueryableIQueryable<T> 查询编译为表达式树。IQueryable and IQueryable<T> queries are compiled to expression trees. 有关详细信息,请参阅表达式树For more information, see Expression trees.

后续步骤Next steps

若要详细了解 LINQ,请先自行熟悉查询表达式基础知识中的一些基本概念,然后再阅读感兴趣的 LINQ 技术的相关文档:To learn more details about LINQ, start by becoming familiar with some basic concepts in Query expression basics, and then read the documentation for the LINQ technology in which you are interested:

若要更深入地全面了解 LINQ,请参阅 C# 中的 LINQTo gain a deeper understanding of LINQ in general, see LINQ in C#.

若要开始在 C# 中使用 LINQ,请参阅教程使用 LINQTo start working with LINQ in C#, see the tutorial Working with LINQ.

请参阅See also