2009年6月9日 星期二

[LINQ ] 初探

簡介

LINQ 是 Microsoft 開發出來專門用來處理集合資訊用的技術,什麼叫做集合資訊呢?

舉凡 Database、XML、Object、DataSet、Array、Collection .... 等都可以算是集合資訊

而我們再開發軟體時,資料來源也就差不多是上面這些,但每一種資料來源都有很多額外的知識必須要學..... Database 是一門學問、XML 又是一門學問 ...

想像一下若是可以用同一套語法來存取以上這些資料來源,不是很迷人的事情嗎?

而 LINQ 就是為了這個目的而產生的!

瞭解一下 LINQ 的目標就可以知道他有多酷了:(from LINQ In Action)
  1. Integrated objects, relational data, and XML (這當然是首要目的)

  2. SQL and XQuery-like power in C# and VB (整合進 C# & VB.NET 囉)

  3. Extensibility model for languages (提供其他語言的擴充性)

  4. Extensibility model for multiple data sources (當然也提供了不同資料來源的擴充性)

  5. Type safety (透過 compile-time 檢查)

  6. Extensive IntelliSense support (enabled by strong-typing) (這對開發者肯定是一大福音啊!)

  7. Debug support (這功能沒有怎麼可以呢?)



使用範例

首先來個使用範例,LINQ to Object !



using System;
using System.Linq;

namespace HelloLinq
{
class Program
{
static void Main(string[] args)
{
//string array
string[] words = { "hello", "wonderful", "linq", "beautiful", "world" };

//取得陣列中字串長度小於等於 5 的字串
var shortwords = from word in words
where word.Length <= 5
select word;
/* hello
linq
world */
foreach (var word in shortwords)
Console.WriteLine(word);


//依照字串長度分群組
var groups = from word in words
orderby word ascending
group word by word.Length into lengthGroups
orderby lengthGroups.Key descending
select new { Length = lengthGroups.Key, Words = lengthGroups };
/*
words of length 9
beautiful
wonderful
words of length 5
hello
world
words of length 4
linq
*/
foreach (var group in groups)
{
Console.WriteLine("words of length " + group.Length);
foreach (string word in group.Words)
Console.WriteLine(" " + word);
}

Console.ReadLine();
}
}
}




看到範例的第一個部分,也許有人會覺得沒有 LINQ 也是很好寫吧!

但第二部份,不是用 LINQ 的話,可就很費工囉!

然而,範例雖然簡單,還是可以看出 LINQ 的語法真的是相當直覺......加上 VS.NET 的 IntelliSense....(難怪 MS 的開發工具這麼多人用.....)


接著以下的範例,可以看出 LINQ 如何以幾乎無縫的方式整合進 C#(VB.NET 也行啦) 中,搭配 XML API 來產生 XML 文件:


using System;
using System.Linq;
using System.Xml.Linq;

namespace HelloLinqToXml
{
class Book
{
public string Publisher;
public string Title;
public int Year;

public Book(string title, string publisher, int year)
{
Title = title;
Publisher = publisher;
Year = year;
}
}

class Program
{
static void Main(string[] args)
{
//定義 object collection
Book[] books = new Book[] {
new Book("Ajax in Action", "Manning", 2005),
new Book("Windows Forms in Action", "Manning", 2006),
new Book("RSS and Atom in Action", "Manning", 2006)
};

//從 object collection 中取得資料後,並搭配 XML API 產生 XML 文件
XElement xml = new XElement("books",
from book in books
where book.Year == 2006
select new XElement("book",
new XAttribute("title", book.Title),
new XElement("publisher", book.Publisher)));

Console.WriteLine(xml);
Console.ReadLine();
}
}
}




最後一個部分則是 LINQ to SQL,此處以 NorthWind 為範例資料庫:


using System;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data.SqlClient;

namespace HelloLinqToSql
{
class Program
{
static void Main(string[] args)
{
//設定資料來源
DataContext db = new DataContext(new SqlConnection("Server=CIC-GODLEON\\SQLEXPRESS;Database=northwind;Trusted_Connection=True;"));

//透過 LINQ 來取得資料
var contacts =
from contact in db.GetTable()
where contact.City == "Paris"
select contact;

foreach (var contact in contacts)
Console.WriteLine("Bonjour " + contact.Name);

Console.ReadLine();

}
}


///
/// 必須透過設定 attribute 的方式指定 class 和 DB table 的 mapping
/// 此處指定對應到 Customers 資料表
///

[Table(Name="Customers")]
class Contact
{
///
/// 同樣內部的設定也必須要透過 attribute 的方式設定 mapping
///


//未指定則對應到同名(CustomerID)欄位
[Column(IsPrimaryKey=true)]
public string CustomerID { get; set; }

//指定對應到 ContactName 欄位
[Column(Name="ContactName")]
public string Name { get; set; }

//對應 City 欄位
[Column]
public string City { get; set; }
}
}





參考資料

沒有留言:

張貼留言