Linq,中文叫做Language-integrated Query (LINQ)。直白的理解就是:將對資料的查詢整合到語言中去(如C#)。
通常,我們從資料庫中操作,需要根據不同的條件式篩選出不同的記錄出來。對應不同的條件,我們寫不同的函數來過濾相應的記錄。這樣將會相當麻煩。每當相按某一條件過濾查詢時,就要擴充一個相應方法。如果直接像在資料庫中使用sql語句來該多方便呀。什麼函數都不用寫。只按select from where order by 就搞定了。
Linq,正是提供了這樣的功能,將類似於sql中的這種查詢,提供到了C#中。於是我們可以很“無恥”的這樣擷取資料:
一個Book類,這個類是一個映射類,和資料庫表相映射:
[Table]
public class Book
{
///
/// 圖書名稱
///
[Column]
public string Title { get; set; }
///
/// 單價
///
[Column(DbType = "numeric(5, 2)")]
public float Price { get; set; }
///
/// 作者
///
[Column]
public string Author { get; set; }
///
/// ISBN號
///
[Column]
public string ISBN { get; set; }
}
資料查詢:
DataContext db = new DataContext("Data Source=localhost;Initial Catalog=db;User ID=sa;Password=sa");
var result = from book in db.GetTable<Book>()
where book.Price > 50
orderby book.Price
select new { Key = book.Title, Value = book.Price };
foreach (var item in result)
Console.WriteLine("Key:{0}-Value:{1}",item.Key,item.Value.ToString());
哈哈,是不是就像使用sql一樣。這樣我們就可省略自己定義過濾函數,直接寫一個類sql搞定。
這是最初步的理解。