Linq 简明教程

LINQ - Overview

由于缺少明确的路径,并需要精通 SQL、Web 服务、XQuery 等多项技术,世界各地的开发人员在查询数据时总会遇到问题。

Developers across the world have always encountered problems in querying data because of the lack of a defined path and need to master a multiple of technologies like SQL, Web Services, XQuery, etc.

LINQ(语言集成查询)由 Anders Hejlsberg 设计,在 Visual Studio 2008 中引入,允许编写查询,即使不知道 SQL、XML 等查询语言。可为不同数据类型编写 LINQ 查询。

Introduced in Visual Studio 2008 and designed by Anders Hejlsberg, LINQ (Language Integrated Query) allows writing queries even without the knowledge of query languages like SQL, XML etc. LINQ queries can be written for diverse data types.

Example of a LINQ query

C

using System;
using System.Linq;

class Program {
   static void Main() {

      string[] words = {"hello", "wonderful", "LINQ", "beautiful", "world"};

      //Get only short words
      var shortWords = from word in words where word.Length <= 5 select word;

      //Print each word out
      foreach (var word in shortWords) {
         Console.WriteLine(word);
      }

      Console.ReadLine();
   }
}

VB

Module Module1
   Sub Main()
      Dim words As String() = {"hello", "wonderful", "LINQ", "beautiful", "world"}

      ' Get only short words
      Dim shortWords = From word In words _ Where word.Length <= 5 _ Select word

      ' Print each word out.

      For Each word In shortWords
         Console.WriteLine(word)
      Next

      Console.ReadLine()
   End Sub
End Module

当以上 C# 或 VB 代码被编译并执行时,它会生成以下结果 -

When the above code of C# or VB is compiled and executed, it produces the following result −

hello
LINQ
world

Syntax of LINQ

LINQ 的语法有两种。它们如下所示。

There are two syntaxes of LINQ. These are the following ones.

Lamda (Method) Syntax

var longWords = words.Where( w ⇒ w.length > 10);
Dim longWords = words.Where(Function(w) w.length > 10)

Query (Comprehension) Syntax

var longwords = from w in words where w.length > 10;
Dim longwords = from w in words where w.length > 10

Types of LINQ

LINQ 的类型概述如下。

The types of LINQ are mentioned below in brief.

  1. LINQ to Objects

  2. LINQ to XML(XLINQ)

  3. LINQ to DataSet

  4. LINQ to SQL (DLINQ)

  5. LINQ to Entities

除了上述类型之外,还有一个名为 PLINQ 的 LINQ 类型,它是 Microsoft 提供的并行 LINQ。

Apart from the above, there is also a LINQ type named PLINQ which is Microsoft’s parallel LINQ.

LINQ Architecture in .NET

LINQ 具有一个 3 层架构,其中最上层由语言扩展组成,最底层由通常实现 IEnumerable 或 IQueryable 通用接口的对象(数据源)组成。该架构如下所示。

LINQ has a 3-layered architecture in which the uppermost layer consists of the language extensions and the bottom layer consists of data sources that are typically objects implementing IEnumerable <T> or IQueryable <T> generic interfaces. The architecture is shown below.

linq architecture

Query Expressions

查询表达式只不过是一个 LINQ 查询,它以类似于 SQL 的形式表示,带有 Select、Where 和 OrderBy 等查询运算符。查询表达式通常以关键词“From”开头。

Query expression is nothing but a LINQ query, expressed in a form similar to that of SQL with query operators like Select, Where and OrderBy. Query expressions usually start with the keyword "From".

要访问标准 LINQ 查询运算符,应默认导入命名空间 System.Query。这些表达式写在声明式查询语法内,该语法是 C# 3.0 的。

To access standard LINQ query operators, the namespace System.Query should be imported by default. These expressions are written within a declarative query syntax which was C# 3.0.

下面是一个示例,展示了一个完整的查询操作,该操作包括数据源创建、查询表达式定义和查询执行。

Below is an example to show a complete query operation which consists of data source creation, query expression definition and query execution.

C

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Operators {
   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 + " ");
         }

         Console.ReadLine();
      }
   }
}

编译并执行上述代码后,将产生以下结果 −

When the above code is compiled and executed, it produces the following result −

97 92 81

Extension Methods

使用 .NET 3.5 引入,仅在静态类中声明扩展方法,并允许将自定义方法包含到对象中,以执行一些精确的查询操作,而无需成为该类的实际成员。这些方法还可以重载。

Introduced with .NET 3.5, Extension methods are declared in static classes only and allow inclusion of custom methods to objects to perform some precise query operations to extend a class without being an actual member of that class. These can be overloaded also.

简而言之,扩展方法用于将查询表达式转换为传统方法调用(面向对象)。

In a nutshell, extension methods are used to translate query expressions into traditional method calls (object-oriented).

Difference between LINQ and Stored Procedure

LINQ 和存储过程之间有很多差异。这些差异如下所述。

There is an array of differences existing between LINQ and Stored procedures. These differences are mentioned below.

  1. Stored procedures are much faster than a LINQ query as they follow an expected execution plan.

  2. It is easy to avoid run-time errors while executing a LINQ query than in comparison to a stored procedure as the former has Visual Studio’s Intellisense support as well as full-type checking during compile-time.

  3. LINQ allows debugging by making use of .NET debugger which is not in case of stored procedures.

  4. LINQ offers support for multiple databases in contrast to stored procedures, where it is essential to re-write the code for diverse types of databases.

  5. Deployment of LINQ based solution is easy and simple in comparison to deployment of a set of stored procedures.

Need For LINQ

在 LINQ 之前,有必要学习 C#、SQL 和将两者结合在一起形成完整应用程序的各种 API。由于这些数据源和编程语言存在阻抗不匹配,因此需要简短的编码。

Prior to LINQ, it was essential to learn C#, SQL, and various APIs that bind together the both to form a complete application. Since, these data sources and programming languages face an impedance mismatch; a need of short coding is felt.

下面是一个示例,说明在 LINQ 出现之前,开发人员在查询数据时使用了多少种不同的技术。

Below is an example of how many diverse techniques were used by the developers while querying a data before the advent of LINQ.

SqlConnection sqlConnection = new SqlConnection(connectString);
SqlConnection.Open();

System.Data.SqlClient.SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;

sqlCommand.CommandText = "Select * from Customer";
return sqlCommand.ExecuteReader (CommandBehavior.CloseConnection)

有趣的是,在这些特色的代码行中,查询仅由最后两行定义。使用 LINQ,相同的 data 查询可以用可读的彩色彩色形式编写,如下所示,而且时间非常短。

Interestingly, out of the featured code lines, query gets defined only by the last two. Using LINQ, the same data query can be written in a readable color-coded form like the following one mentioned below that too in a very less time.

Northwind db = new Northwind(@"C:\Data\Northwnd.mdf");
var query = from c in db.Customers select c;

Advantages of LINQ

LINQ 提供了许多优势,其中首要优势是其强大的表达能力,使开发人员能够以声明方式表达。以下列出了 LINQ 的其他一些优势。

LINQ offers a host of advantages and among them the foremost is its powerful expressiveness which enables developers to express declaratively. Some of the other advantages of LINQ are given below.

  1. LINQ offers syntax highlighting that proves helpful to find out mistakes during design time.

  2. LINQ offers IntelliSense which means writing more accurate queries easily.

  3. Writing codes is quite faster in LINQ and thus development time also gets reduced significantly.

  4. LINQ makes easy debugging due to its integration in the C# language.

  5. Viewing relationship between two tables is easy with LINQ due to its hierarchical feature and this enables composing queries joining multiple tables in less time.

  6. LINQ allows usage of a single LINQ syntax while querying many diverse data sources and this is mainly because of its unitive foundation.

  7. LINQ is extensible that means it is possible to use knowledge of LINQ to querying new data source types.

  8. LINQ offers the facility of joining several data sources in a single query as well as breaking complex problems into a set of short queries easy to debug.

  9. LINQ offers easy transformation for conversion of one data type to another like transforming SQL data to XML data.