從本節開始,本文正式更名為C#3.0入門系列。先發布一則消息,VS2007 Beta版本已經發布咯,下載地址:
http://www.microsoft.com/downloads/details.ASPx?FamilyID=1FF0B35D-0C4A-40B4-915A-5331E11C39E6&displaylang=en
大家快去下載呀,我也好和大家一起體驗該版本最新功能呀。
dlinq也更名為linq to sql.本文也跟著做相應變化,稍候,我會去更新前面的文章。我們先接著講linq的語法。
Select操作
最簡單的
1, var q =
from c in db.Customers
select c.ContactName;
匿名類的
1, var q =
from c in db.Customers
select new {c.ContactName, c.Phone};
2, var q =
from e in db.Employees
select new {Name = e.FirstName + " " + e.LastName, Phone = e.HomePhone};
3, var q =
from p in db.Products
select new {p.ProductID, HalfPrice = p.UnitPrice / 2};
條件的
var q =
from p in db.Products
select new {p.ProductName, Availability = p.UnitsInStock - p.UnitsOnOrder < 0 ? "Out Of Stock": "In Stock"};
這種條件的會被翻譯成sql中{case when condition then else}的。
name type形式的:
var q =
from e in db.Employees
select new Name {FirstName = e.FirstName, LastName = e.LastName};
只所以是name type的,是因為Name類是已經定義好的,也就是說,你可以用這種方式,返回你需要類型的對象集.
shaped形式的:
var q =
from c in db.Customers
select new {
c.CustomerID,
CompanyInfo = new {c.CompanyName, c.City, c.Country},
ContactInfo = new {c.ContactName, c.ContactTitle}
};