查询语句汇聚:
var 构建匿名类型2 = from emp in ctx.Employees
select new
{
姓名 = emp.LastName + emp.FirstName,
雇用年 = emp.HireDate.Value.Year
};
var select带条件 = from o in ctx.Orders
select new
{
订单号 = o.OrderID,
是否超重 = o.Freight > 100 ? "是" : "否"
};
var 多条件 = from c in ctx.Customers
where c.Country == "France" && c.Orders.Count > 5
select new
{
国家 = c.Country,
城市 = c.City,
订单数 = c.Orders.Count
};
var 排序 = from emp in ctx.Employees
where emp.Employees.Count == 0
orderby emp.HireDate.Value.Year descending, emp.FirstName ascending
select new
{
雇用年 = emp.HireDate.Value.Year,
名 = emp.FirstName
};
var 分页 = (from c in ctx.Customers select c).Skip(10).Take(10);//Skip:跳到第10页,一页10条记录
var 匿名类型分组 = from c in ctx.Customers
group c by new { c.City, c.Country } into g
orderby g.Key.Country, g.Key.City
select new
{
国家 = g.Key.Country,
城市 = g.Key.City
};
var 按照条件分组 = from o in ctx.Orders
group o by new { 条件 = o.Freight > 100 } into g
select new
{
数量 = g.Count(),
是否超重 = g.Key.条件 ? "是" : "否"
};
var 过滤相同项 = (from c in ctx.Customers orderby c.Country select c.Country).Distinct();
查询城市是A打头和城市包含A的顾客并按照顾客名字排序
var 连接并且过滤相同项 = (from c in ctx.Customers where c.City.Contains("A") select c).Union
(from c in ctx.Customers where c.ContactName.StartsWith("A") select c).OrderBy(c => c.ContactName);
查询城市是A打头和城市包含A的顾客并按照顾客名字排序,相同的顾客信息不会过滤
var 连接并且不过滤相同项 = (from c in ctx.Customers where c.City.Contains("A") select c).Concat
(from c in ctx.Customers where c.ContactName.StartsWith("A") select c).OrderBy(c => c.ContactName);
查询城市包含A的顾客并从中删除城市以A开头的顾客,并按照顾客名字排序
var 排除相交项 = (from c in ctx.Customers where c.City.Contains("A") select c).Except
(from c in ctx.Customers where c.ContactName.StartsWith("A") select c).OrderBy(c => c.ContactName);
子查询:
查询订单数超过5的顾客信息
var 子查询 = from c in ctx.Customers
where
(from o in ctx.Orders group o by o.CustomerID into o where o.Count() > 5 select o.Key).Contains(c.CustomerID)
select c;
in操作:查询指定城市中的客户
var in操作 = from c in ctx.Customers
where new string[] { "Brandenburg", "Cowes", "Stavern" }.Contains(c.City)
select c;
join操作:内连接,没有分类的产品查询不到
var innerjoin = from p in ctx.Products
join c in ctx.Categories
on p.CategoryID equals c.CategoryID
select p.ProductName;