-
LINQ
(語言集成查詢)
鎖定
語言集成查詢(英語:Language Integrated Query,縮寫:LINQ),發音"link",是微軟的一項技術,新增一種自然查詢的SQL語法到.NET Framework的編程語言中,當前可支持C#以及Visual Basic .NET語言。2007年11月19日隨.NET Framework 3.5發佈了LINQ技術。
包括LINQ to Objects、LINQ to SQL、LINQ to Datasets、LINQ to Entities、LINQ to Data Source、LINQ to XML/XSD等。
- 中文名
- 語言集成查詢
- 外文名
- Language Integrated Query
- 開發公司
- 微軟
- 語 種
- C#,Visual Basic
目錄
LINQ基本含義
從技術角度而言,LINQ定義了大約40個查詢操作符,如select、from、in、where以及order by(C#中)。使用這些操作符可以編寫查詢語句。不過,這些查詢還可以基於很多類型的數據,每個數據類型都需要一個單獨的LINQ類型。
經過了最近 20 年,面向對象編程技術( object-oriented (OO) programming technologies )在工業領域的應用已經進入了一個穩定的發展階段。程序員都已經認同像 類(classes)、對象(objects)、方法(methods)這樣的語言特性。考察下一代的技術,一個新的編程技術的重大挑戰開始呈現出來,即面向對象技術誕生以來並沒有解決降低訪問和整合信息數據( accessing and integrating information )的複雜度的問題。其中兩個最主要訪問的數據源與數據庫(database)和XML(標準通用標記語言下的一個應用)相關。
LINQ 提供了一條更常規的途徑即給.Net Framework添加一些可以應用於所有信息源( all sources of information )的具有多種用途( general-purpose )的語法查詢特性( query facilities ),這是比向開發語言和運行時( runtime )添加一些關係數據( relational )特性或者類似 XML 特性( XML-specific )更好的方式。這些語法特性就叫做 .NET Language Integrated Query (LINQ) 。
包含 DLinq 和 XLinq。
LINQ語言風格
LINQ新增了多項語言的風格,來展示出查詢語言的擴展性,例如:C#:
LINQ匿名類型
匿名類型(Anonymous type)是C# 3.0與Visual Basic 9.0新增的功能,它允許開發人員可以使用不具類型的方式創建新的數據結構,而真正的類型在編譯時期,由C# (或VB) Compiler自動產生,並寫入編譯目標文件中,它可以讓開發人員能夠很簡單利用匿名類型創建對象,LINQ中的select指令即是利用這種特性來創建回傳對象。
匿名類型本質上是表達元組(tuple),採用值語義
[1]
。
下列使用匿名類型的代碼:
[WebGet] public IQueryable<Categories> GetCategoryByName(string CategoryName) { try{ var query = base.CurrentDataSource.Categories.Where ("it.CategoryName = @Name", new ObjectParameter[] { new ObjectParameter("Name", CategoryName) }); } catch (Exception) { throw; } return query; }
會由編譯器改寫為:
[WebGet] public IQueryable<Categories> GetCategoryByName(string CategoryName) { IQueryable<Categories> CS$1$0000; // 由編譯器改寫而成。 try { CS$1$0000 = base.CurrentDataSource.Categories.Where ("it.CategoryName = @Name", new ObjectParameter[] { new ObjectParameter("Name", CategoryName) }); } catch (Exception) { throw; } return CS$1$0000; }
LINQ標準查詢運算符
操作符 | 類別 | 語義 | 示例 |
---|---|---|---|
Where | 篩選操作符(Restriction) | Where(Predicate) | Dim lowNums = numbers.Where(Function(num) num < 5) |
Select | 投影操作符(Projection) | Select(匿名函數) | Dim lowNums = numbers.Select(Function(num) num*num) |
SelectMany | 投影操作符(Projection) | 返回多行結果,用於多表的交叉連接(cross join) | Dim res = Employees.SelectMany(Function(e) e.Family.Select(Function(c)c.name)) |
Skip | 分塊操作符(Partitioning) | 跳過前n個元素 | Dim res=data.Skip(4) |
SkipWhile | 分塊操作符(Partitioning) | 跳過起始處使條件為真的所有元素 | Dim res=data.SkipWhile(Function(i) i%2 = 0) |
Take | 分塊操作符(Partitioning) | 返回開頭之處的n個元素 | Dim res=data.Take(3) |
TakeWhile | 分塊操作符(Partitioning) | 返回起始處使條件為真的所有元素 | Dim res=data.TakeWhile(Function(i) i%3 = 0) |
Join | 連接操作符 | 內連接兩個或多個表,僅限於Equals運算符 | from sup in suppliers join cust in customers on sup.Country equals cust.Country |
GroupJoin | 連接操作符 | 類似於LEFT OUTER JOIN,右側集合匹配於左側集合鍵值的元素被分組 | From cust In customers Group Join ord In orders On cust.CustomerID Equals ord.CustomerID Into CustomerOrders = Group, OrderTotal = Sum(ord.Total) |
Concate | 合併操作符 | 用於連接兩個序列 | returnValue = firstSeq.Concat(secondSeq) |
OrderBy | 排序操作符(Ordering) | Dim query As IEnumerable(Of Person) = Persons.OrderBy(Function(p) p.Age) | |
OrderByDescending | 排序操作符(Ordering) | ||
ThenBy | 排序操作符(Ordering) | ||
ThenByDescending | 排序操作符(Ordering) | ||
Reverse | 排序操作符(Ordering) | ||
GroupBy | 分組操作符 | Dim numbers = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0} Dim numberGroups = From num In numbers Group num By remainder5 = (num Mod 5) Into numGroup = Group Select New With {.Remainder = remainder5, .numbers = numGroup} | |
Distinct | 集合操作符 | 去重複 | |
Union | 集合操作符 | 集合並 | |
Intersect | 集合操作符 | 集合交 | |
Except | 集合操作符 | 集合差 | |
AsEnumerable | 轉換操作符 | 用於把一個IEnumerable的派生類型轉化為IEnumerable類型 | |
AsQueryable | 轉換操作符 | IEnumerable(Of T)轉化為IQueryable(Of T). | |
ToArray | 轉換操作符 | 轉換為數組 | |
ToList | 轉換操作符 | 轉換為List | |
ToDictionary | 轉換操作符 | 轉換為一對一的字典(鍵-值對的集合) | |
ToLookup | 轉換操作符 | 轉換為一對多的字典(鍵-值集的集合) | |
OfType | 轉換操作符 | 獲取指定類型的元素組成一個數組 | object[] numbers = { null, 1.0, "two", 3, "four", 5, "six", 7.0 }; var doubles = numbers.OfType<double>(); |
Cast | 轉換操作符 | 把序列的所有元素轉換為指定類型 | |
SequenceEqual | 相等操作符 | 兩個序列的元素依次相同返回真。使用元素所屬類的IEqualityComparer(Of T) 泛型界面做相等比較 | |
First | 元素操作符 | 返回序列第一個元素(或滿足條件第一個元素),沒有則異常 | |
FirstOrDefault | 元素操作符 | 返回序列第一個元素,沒有則返回空或默認值 | |
Last | 元素操作符 | 返回序列最後一個元素,沒有則異常 | |
LastOrDefault | 元素操作符 | 返回序列最後一個元素,沒有則返回空或默認值 | |
Single | 元素操作符 | 返回序列唯一元素,如果沒有元素或多個元素則異常 | |
SingleOrDefault | 元素操作符 | 返回序列唯一元素,如果沒有元素或多個元素則空或默認值 | |
ElementAt | 元素操作符 | 返回序列指定元素,失敗則異常 | |
ElementAtOrDefault | 元素操作符 | 返回序列指定元素,失敗則空或默認值 | |
DefaultIfEmpty | 元素操作符 | 返回序列,如果序列為空則返回元素的默認值 | For Each number As Integer In numbers.DefaultIfEmpty()〈br> output.AppendLine(number) Next |
All | 序列元素數量操作符 | 序列所有元素滿足條件則為真 | |
Any | 序列元素數量操作符 | 序列有一個元素滿足條件則為真 | |
Contains | 序列元素數量操作符 | 是否包含一個元素 | |
Count | 統計操作符 | 計數,可選一個謂詞 | int oddNumbers = numbers.Count(n => n% 2 == 1); |
LongCount | 統計操作符 | 計數,返回Int64類型 | |
Sum | 統計操作符 | 求和,可選對一個lambda函數表達式 | double totalChars = words.Sum(w => w.Length); |
Min | 統計操作符 | 最小值,可選對一個lambda函數表達式 | int shortestWord = words.Min(w => w.Length); |
Max | 統計操作符 | ||
Average | 統計操作符 | ||
Aggregate | 統計操作符 | 參數為一個委託,在序列的每個元素上執行該委託。委託的第一個參數為當前累計值,第二個參數為當前元素,返回值為新的累計值 | Dim reversed As String = words.Aggregate(Function(ByVal current, ByVal word) word & " " & current) |
equals/Equals | 關鍵字 | 用於Join子句 | |
from/From | 關鍵字 | ||
in/In | 關鍵字 | 指出數據源 | |
into/Into | 關鍵字 | 用於Group By子句 | |
key | 關鍵字 | 用於Group By子句的無名類型 | |
let | 關鍵字 | 給表達式定義別名 | From prod In products Let Discount = prod.UnitPrice * 0.1 Where Discount >= 50 Select prod.ProductName, prod.UnitPrice, Discount |
Group | 關鍵字 | 在GroupBy子句的Into中用於辨識分組結果 | From num In numbers Group num By remainder5 = (num Mod 5) Into Group |
Range | 方法 | 產生一個整數序列 | From n In Enumerable.Range(100, 50) |
Repeat | 方法 | 產生一個整數序列 | From n In Enumerable.Repeat(7, 10) |
LINQLINQ的各式言語支持度
下列的言語支持LINQ。
LINQLINQ的示例
一個簡單例子:
using System; using System.Linq;namespace DuckTyping{ internal class Program { private static void Main() { int[] array = { 1, 5, 2, 10, 7 }; // Select squares of all odd numbers in the array sorted in descending order var results = from x in array where x % 2 == 1 orderby x descending select x * x; foreach (var result in results) { Console.WriteLine(result); } } } }
輸出: 49 25 1
另一個例子:
// the Northwind type is a subclass of DataContext created by SQLMetal // Northwind.Orders is of type Table<Order> // Northwind.Customers is of type Table<Customer>Northwind db = new Northwind(connectionString); // use 'var' keyword because there is no name for the resultant type of the projection var q = from o in db.Orders from c in db.Customers where o.Quality == "200" && (o.CustomerID == c.CustomerID) select new { o.DueDate, c.CompanyName, c.ItemID, c.ItemName }; // q is now an IEnumerable<T>, where T is the anonymous type generated by the compilerforeach (var t in q){ // t is strongly typed, even if we can't name the type at design time Console.WriteLine("DueDate Type = {0}", t.DueDate.GetType()); Console.WriteLine("CompanyName (lowercased) = {0}", t.CompanyName.ToLower()); Console.WriteLine("ItemID * 2 = {0}", t.ItemID * 2); }
LINQVisual Studio支持
LINQ當前由Visual Studio2008、2010、2012、2013、2015、2017支持。
LINQ語言擴展
微軟同樣提供了LINQExtender,允許用户在不瞭解LINQ實現細節的情況下,編寫自己的LINQ擴展。 如:LINQ to Twitter,LINQ to Oracle,LINQ to Active Directory等。