Language Integrated Query (LINQ)Language Integrated Query (LINQ)

Language Integrated Query (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 Object)、關聯式資料庫 (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 中針對 SQL Server 資料庫以 C# 和 Visual Basic 撰寫之部分完成的 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,請參閱使用 LINQ 教學課程。To start working with LINQ in C#, see the tutorial Working with LINQ.