Linq的常见查询语句示例

 查询语句汇聚:
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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT流渊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值