LINQ Customers淺談
在向大家詳細(xì)介紹LINQ Customers之前,首先讓大家了解下 LINQ 究竟是什么,然后全面介紹LINQ Customers。
LINQ 究竟是什么?
LINQ,全名叫 Language INtegrated Query,它把查詢(Query)和設(shè)置(set operations)等操作封裝起來,就像.NET語言里如 C# 或 VB ***實(shí)現(xiàn)的 SQL statements 查詢語句一樣。
Query 表達(dá)式,也就是你所熟悉并熱衷于使用的 SQL 語法如“from”、“where”和“select”等以及其他 C# 和 VB 里***實(shí)現(xiàn)的查詢語法。不僅如此,Query 表達(dá)式還可用于跨應(yīng)用領(lǐng)域查詢數(shù)據(jù)。在下面的例子中,示范如何查詢對(duì)象數(shù)據(jù)(Objects),就如同查詢數(shù)據(jù)庫(kù)(Database)中的數(shù)據(jù)一樣容易。
用LINQ編寫的代碼是什么樣子呢?
下面的例子示范查詢一個(gè)string數(shù)據(jù)列表(list),并返回長(zhǎng)度為 5 的 string 數(shù)據(jù)。
- using System;
- using System.Query;
- using Danielfe;
- class Program
- {
- static void Main(string[] args)
- {
- string[] aBunchOfWords = {"One","Two", "Hello",
- "World", "Four", "Five"};
- var result =
- from s in aBunchOfWords // query the string array
- where s.Length == 5 // for all words with length = 5
- select s; // and return the string
- //PrintToConsole is an Extension method that prints the value
- result.Print();
- }
- }
LINQ 的奇妙之處在于你可以用它來查詢?nèi)魏螖?shù)據(jù)。下面的例子示范從 SQL Server 2005 中查詢所有 Title 長(zhǎng)度為 5 的 Customer 數(shù)據(jù):
- using System;
- using System.Query;
- using Danielfe;
- using System.Data.DLinq; //DLinq is LINQ for Databases
- using nwind; //Custom namespace that is tool generated
- class Program
- {
- static void Main(string[] args)
- {
- Northwind db = new Northwind("Data Source=(local);
- Initial Catalog=Northwind;Integrated Security=True");
- Table<Customers> allCustomers = db.GetTable<Customers>();
- var result =
- from c in allCustomers
- where c.ContactTitle.Length == 5
- select c.ContactName;
- result.Print();
- }
- }
LINQ Customers類是一個(gè)可以讓你的程序訪問的對(duì)應(yīng)于數(shù)據(jù)庫(kù)表(table) 結(jié)構(gòu)的自動(dòng)生成的類。上面代碼的前兩行是建立一個(gè)數(shù)據(jù)庫(kù)連接并獲取LINQ Customers表的數(shù)據(jù),下一行是查詢所有 ContactTitle 的字符串長(zhǎng)度為 5 的LINQ Customers并返回其 ContactName 數(shù)據(jù),再輸出到屏幕。
簡(jiǎn)單的說,LINQ 可以通過一個(gè)統(tǒng)一的標(biāo)準(zhǔn)的方式(類似 SQL 查詢語句)很輕松的訪問任何一種數(shù)據(jù)源。
【編輯推薦】