代码改变世界

關於Linq框架SQL語句的寫法一(where的使用)

2009-10-28 17:00  北冥有魚,其名為坤、  阅读(1022)  评论(2编辑  收藏  举报

where的操作
適用場景:實現過濾,查詢等功能.
說明:與SQL命令中的Where作用相似,都是起到範圍限定也就是過濾的作用,而判斷條件就是他們後面接的子句.
where操作包括三種形式,分別是:簡單形式,關係條件形式,.First()形式,下麵分別舉例說明:
1.簡單形式.
  例如:使用where篩選在倫敦的客戶. 

var q = from c in db.Customers where c.City == "London" select c;

  例如:篩選1994年之後雇傭的雇員. 

var q = from c in db.Empoleeys where c.HireDate >= new Date(1994,1,1) select c;

2.關係條件形式。
  例如:篩選庫存量在訂貨水平之下但未斷貨的產品.  

var q = from c in db.Product where c.UnitsInStock <= p.ReorderLevel && !p.Discontinued
    select c;

  又例如:篩選出UnitPrice大於10或者已經停產的產品.  

var q = from p in p.Product where UnitPrice < 10 || p.Discontinued select p;

  下麵這個例子是兩次調用where篩選出UnitPrice大於10或者已經停產的產品.

var q =
    db.Products.Where(p
=>p.UnitPrice > 10).Where(p=>p.Discontinued);

3.  .First()形式
  说明:其实就是sql中的top 1.
  例如:选择表中的第一个发货方.

Shipper shipper = db.Shipper.First();
  元素:选择CustomerID 为“BONAP”的单个客户
Customer cust = db.Customers.First(c => c.CustomerID == "BONAP");