LINQ對於筆者來說, 優美而濃縮的代碼讓人震驚. 研究LINQ就是在藝術化自己的代碼.
之前只是走馬觀花學會了基本的語法, 但是經常在CSDN看到令人驚訝自歎不如的LINQ代碼, 還是讓人羨慕嫉妒恨, 真有一種心血來潮想追趕的沖動.
所以, 還是決定系統的學習一下LINQ.
(1.4) LINQ to Objects
這是一個簡單的hello world性質的例子.
1 var words = new List<string>() { "hello", "wonderful","linq","beautiful","world"};
2 var res = from s in words
3 where s.Length <= 5
4 select s;
5 Console.WriteLine("輸出串長度<=5的單詞:" + Environment.NewLine);
6 foreach (var m in res)
7 {
8 Console.WriteLine(m);
9 }
10
11 //按字母順序對一個單詞進行排序,然後按照其長度進行分組,並按照其中包含的單詞長度逆序排列各組.
12 Console.WriteLine(Environment.NewLine + "按長度分組排序顯示:" + Environment.NewLine);
13 var res1 = from s in words
14 orderby s ascending //ascending升序
15 group s by s.Length into lengroup
16 orderby lengroup.Key descending //descending降序
17 select new { Length = lengroup.Key, Words = lengroup };
18 foreach (var m in res1)
19 {
20 Console.WriteLine("單詞長度:" + m.Length);
21 foreach (var str in m.Words)
22 Console.WriteLine(" " + str);
23 }
結果如下圖:

現在, 對於List<>進行數據處理, 我就只用 LINQ to Objects了.
(1.5) LINQ to XML 初步
上代碼:
1 class Book
2 {
3 public string Publisher;
4 public string Title;
5 public int Year;
6
7 public Book(string title, string publisher, int year)
8 {
9 this.Title = title;
10 this.Publisher = publisher;
11 this.Year = year;
12 }
13 }
1 Book[] books = new Book[]{
2 new Book("Ajax in Action","Manning",2005),
3 new Book("Windows Froms in Action","Manning",2006),
4 new Book("Rss and Atom in Action","Manning",2006)
5 };
6 XElement xml = new XElement("books",
7 from s in books
8 where s.Year == 2006
9 select new XElement("book",
10 new XAttribute("title", s.Title),
11 new XElement("publisher", s.Publisher)
12 ));
13 Console.WriteLine(xml);
結果如下圖:

看上去LINQ to XML從表達上比DOM更加形象.這代碼和它生成的XML結構基本上是"所見即所得"的.
另外, LINQ to XML是以元素為中心的, 而DOM是以文檔為中心的.
(1.6) LINQ to SQL
下面的代碼的幾點說明:
1. 首先需要定義一個實體類, 用以和Northwind數據的Contacts數據表關聯起來.
本文所用的Northwind數據是微軟提供演示的, 你可以自己去下. 也可以自己創建一個.
2. 自定義屬性 [Table(Name = "Contacts")], 這個你得引入System.data.linq, 否則你懂的.
3. 自定義屬性 [Column(Name = "Name")], 在代碼中用於定義與數據表中列的對應關系.
1 static class HelloLinqToSql
2 {
3 [Table(Name = "Contacts")]
4 public class Contact
5 {
6 [Column(IsPrimaryKey = true)]
7 public int ContactID { get; set; }
8 [Column(Name = "Name")]
9 public string Name { get; set; }
10 [Column]
11 public string City { get; set; }
12 }
13 }
4. DataContext是設備上下文, 你肯定知道是用來傳入連接字符串的
5. 連接字符串中的 security=SSPI 使用windows自帶的安全驗證機制, 不用輸入用戶名與密碼.
6. DataContext.GetTable<>, 這個是泛型的, 注意到沒有? 允許你操作強類型對象.
1 DataContext db = new DataContext(@"server=(local);integrated security=SSPI;database=Northwind");
2
3 var contacts =
4 from contact in db.GetTable<HelloLinqToSql.Contact>()
5 where contact.City == "武漢"
6 select contact;
7
8 Console.WriteLine("查找在武漢的聯系人"+Environment.NewLine);
9 foreach (var contact in contacts)
10 Console.WriteLine("聯系人: " + contact.Name.Trim()+" ID:"+contact.ContactID);
結果如下圖:

這個效果, 真是顛覆了我對關系數據庫操作認知!
下面的事, 都被LINQ承包了:
原創文章,出自"博客園, 豬悟能'S博客" : http://www.cnblogs.com/hackpig/