C#MVC4基础(二)(Linq查询,Lambda表达式)
Linq查询关键字:
语法:
from [type] id in source
[join [type] id in source on expr equals expr [into subGroup]]
[from [type] id in source | let id = expr | where condition]
[orderby ordering,ordering,ordering…]
select expr | group expr by key
[into id query]
PS:粗体表示关键字,[]表示可写可不写
type 类型
id 身份
source 数据源
express 表达
subGroup 子组
condition 条件
ordering 次序
key 钥匙
query 查询
例子:
Products(产品表):Name(产品名称)、CategoryID(产品类别)
Customer(顾客表):CustomerID(顾客编号)、CustomerName(顾客姓名)
Orders(订单表):CustomerID(顾客编号)、OrderDetails(订单明细)
eg1:
查询Products表所有数据:
from p in Products select p
eg2:
查询所有类别为鞋子的产品信息:
from p in Products select p
where p.CategoryID=“鞋子”
select p
eg3:
按产品类别分组查询产品信息:
from p in Products select p
group p by p.CategoryID
eg4:
查询每种产品的数量:
from p in Prouducts
group p by p.CategoryID into g
select new
{
g.Key,
NumProducts = g.Count()
}
eg5:
查询客户的姓名和订单数量
from c in Cutomers
join o in Orders on c.CustomerID equals o.CustemerID into orders
select new
{
c.ContactName,
OrderCount = Orders.Count()
}
eg6:
查询ID号9位以下且名字是三个字的用户
from u in users
let number = u.Username.Length
where u.ID<9 && numbers % 3 == 0
select u
PS:let可用于设置临时变量
Lambda表达式:
属于匿名方法
运算符: =>
替代linq表达式只要 source.关键字(Lambda表达式)就行了
例如:var p = people.Where(s=>s.Age>20);