Linq 實例

1.分頁ide

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

2.分組spa

1)通常分組3d

 
//根據顧客的國家分組,查詢顧客數大於5的國家名和顧客數
var 通常分組 = from c in ctx.Customers group c by c.Country into g where g.Count() > 5 orderby g.Count() descending select new { 國家 = g.Key, 顧客數 = g.Count() };

2)匿名類型分組 (根據國家和城市分組,查詢顧客覆蓋的國家和城市)code

 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

                     };
View Code

3)按條件分組blog

//按照是否超重條件分組,分別查詢訂單數量
var 按照條件分組 = from o in ctx.Orders

                     group o by new { 條件 = o.Freight > 100 } into g

                     select new

                     {

                         數量 = g.Count(),

                         是否超重 = g.Key.條件 ? "" : ""

                     };

3distinct排序

//查詢顧客覆蓋的國家
var 過濾相同項 = (from c in ctx.Customers orderby c.Country select c.Country).Distinct();

4 unionip

//查詢城市是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 concatstring

//查詢城市是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 取相交項it

//查詢城市是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 排除相交項io

//查詢城市包含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() > 5 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;
相關文章
相關標籤/搜索