Linq 实例

1.分页

var 分页 = (from c in ctx.Customers select c).Skip().Take();

2.分组

1)一般分组

//根据顾客的国家分组,查询顾客数大于5的国家名和顾客数
var 一般分组 = from c in ctx.Customers group c by c.Country into g where g.Count() > orderby g.Count() descending select new { 国家 = g.Key, 顾客数 = g.Count() };

2)匿名类型分组 (根据国家和城市分组,查询顾客覆盖的国家和城市)

 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

                     };

3)按条件分组

//按照是否超重条件分组,分别查询订单数量
var 按照条件分组 = from o in ctx.Orders group o by new { 条件 = o.Freight > } into g select new { 数量 = g.Count(), 是否超重 = g.Key.条件 ? "是" : "否" };

3distinct

//查询顾客覆盖的国家
var 过滤相同项 = (from c in ctx.Customers orderby c.Country select c.Country).Distinct();

4 union

//查询城市是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);

5 concat

//查询城市是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);

6 取相交项

//查询城市是A打头的顾客和城市包含A的顾客的交集,并按照顾客名字排序
var 取相交项 = (from c in ctx.Customers where c.City.Contains("A") select c).Intersect (from c in ctx.Customers where c.ContactName.StartsWith("A") select c).OrderBy(c => c.ContactName);

7 排除相交项

//查询城市包含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);

8 子查询

//查询订单数超过5的顾客信息
var 子查询 = from c in ctx.Customers where (from o in ctx.Orders group o by o.CustomerID into o where o.Count() > select o.Key).Contains(c.CustomerID) select c;

9 in操作

//查询指定城市中的客户
var in操作 = from c in ctx.Customers where new string[] { "Brandenburg", "Cowes", "Stavern" }.Contains(c.City) select c;
上一篇:uboot环境配置


下一篇:EntityFramework Core 1.1+ Backing Fields(返回字段)