语言集成查询
维基百科,自由的百科全书
语言集成查询(Language Integrated Query, LINQ),發音 "link",是一项微軟技术,新增一種自然查詢的SQL語法到.NET Framework 的程式語言中,目前可支援 Visual Basic .NET 以及 C# 語言。
目录 |
語言風格 [编辑]
LINQ 新增了多項語言的風格,來展示出查詢語言的擴充性,例如: C#:
匿名型別 [编辑]
匿名型別(Anonymous type)是 C# 3.0 與 Visual Basic 9.0 新增的功能,它允許開發人員可以使用不具型別的方式建立新的資料結構,而真正的型別在編譯時期,由 C# (或 VB) Compiler 自動產生,並寫入編譯目的檔中,它可以讓開發人員能夠很簡單利用匿名型別建立物件,LINQ 中的 select 指令即是利用這種特性來建立回傳物件。
下列使用匿名型別的程式碼:
[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;
}
擴展方法 (Extension method) [编辑]
Lambda表達式 (Lambda expression) [编辑]
表達式樹 (Expression tree) [编辑]
標準查詢運算子 (Standard query operators) [编辑]
LINQ 的各式言語支援度 [编辑]
下列的言語支持 LINQ。
- C# 3.0
- F# 1.1.8.1
- Visual Basic 2008 (9.0)
註:C++/CLI尚未支援LINQ。
LINQ 的範例 [编辑]
// 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 compiler foreach (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); }
Visual Studio支持 [编辑]
LINQ 目前由 Visual Studio 2008、 Visual Studio 2010、Visual Studio 2012支持。
语言扩展 [编辑]
微软同样提供了LINQExtender,允许使用者在不了解LINQ实现细节的情况下,编写自己的LINQ扩展。 如:LINQ to Twitter,LINQ to Oracle,LINQ to Active Directory等
外部連結 [编辑]
- Official Microsoft LINQ Project
- 101 C# LINQ Samples
- 101 Visual Basic LINQ Samples
- Microsoft LINQ forum
- LINQ page on NetFXGuide.com
- LINQ wiki
- LINQExtender
|
|||||||||||||||||||||||||||||||