var q = from c in db.Customers select c.ContactName;
// 保留原名
select new { c.ContactName, c.Phone };
// 重新命名屬性
select new { Name = e.FirstName + " " + e.LastName, Phone = e.HomePhone };
// 包含運算
select new { p.ProductID, HalfPrice = p.UnitPrice / 2 };
select new { p.ProductName,
Availability = p.UnitsInStock - p.UnitsOnOrder < 0 ? "Out Of Stock" : "In Stock" };
select new Name { FirstName = e.FirstName, LastName = e.LastName };
select new {
c.CustomerID,
CompanyInfo = new { c.CompanyName, c.City, c.Country },
ContactInfo = new { c.ContactName, c.ContactTitle }
};
from o in db.Orders
select new {
o.OrderID,
DiscountedProducts = from od in o.OrderDetails
where od.Discount > 0.0
select od,
FreeShippingDiscount = o.Freight
};
回傳物件的 DiscountedProducts 屬性為子集合。
var q = (from c in db.Customers select c.City).Distinct();
// 對應 SQL: SELECT DISTINCT City FROM Customers
where c.City == "London"
where e.HireDate >= new DateTime(1994, 1, 1)
where p.UnitsInStock <= p.ReorderLevel && !p.Discontinued
where p.UnitPrice > 10m || p.Discontinued
多個 Where 鏈式等同 And:
db.Products.Where(p => p.UnitPrice > 10m).Where(p => p.Discontinued)
Customer cust = db.Customers.First(c => c.CustomerID == "BONAP");
Order ord = db.Orders.First(o => o.Freight > 10.00M);
var q = (from c in db.Customers
where c.City == "London"
select c).First();
First() → TOP 1First(predicate) → TOP 1 + WHERE查詢運算式只是宣告,需呼叫 ToList()、ToArray() 或遍歷時才真正執行 SQL。回傳的是物件集合而非資料集。