Linq使用Group By經驗總結

2022-01-22 19:55:24 字數 1665 閱讀 4893

學習linq時,經常會遇到linq使用group by問題,這裡將介紹linq使用group by問題的解決方法。

1.計數

var q =  

from p in

db.products

group p by p.categoryid into g

select

new;

語句描述:linq使用group by和count得到每個categoryid中產品的數量。

說明:先按categoryid歸類,取出categoryid值和各個分類產品的數量。

2.帶條件計數

var q =  

from p in

db.products

group p by p.categoryid into g

select

new;

語句描述:linq使用group by和count得到每個categoryid中斷貨產品的數量。

說明:先按categoryid歸類,取出categoryid值和各個分類產品的斷貨數量。 count函式裡,使用了lambda表示式,lambda表示式中的p,代表這個組裡的乙個元素或物件,即某乙個產品。

3.where限制

var q =  

from p in

db.products

group p by p.categoryid into g

where g.count() >= 10

select

new;

語句描述:根據產品的―id分組,查詢產品數量大於10的id和產品數量。這個示例在group by子句後使用where子句查詢所有至少有10種產品的類別。

說明:在翻譯成sql語句時,在最外層巢狀了where條件。

4.多列(multiple columns)

var categories =  from p in

db.products

group p by

new

into g

select

new;

語句描述:linq使用group by按categoryid和supplierid將產品分組。

說明:既按產品的分類,又按**商分類。在by後面,new出來乙個匿名類。這裡,key其實質是乙個類的物件,key包含兩個property:categoryid、supplierid。用g.key.categoryid可以遍歷categoryid的值。

5.表示式(expression)

var categories =  from p in

db.products

group p by

new into g

select g;

語句描述:linq使用group by返回兩個產品序列。第乙個序列包含單價大於10的產品。第二個序列包含單價小於或等於10的產品。

說明:按產品單價是否大於10分類。其結果分為兩類,大於的是一類,小於及等於為另一類。

使用linq 進行Group by 查詢

上圖是資料庫表 需求是要統計出來 不合格 top 10 其中 ngcode 200代表合格 其他均不合格 sql 語句 如下 select top 10 ngcode as defectcode count 1 as count from dbo tblpassstationdata where n...

linq 資料分組group by

var results from p in persons group p.car by p.personid into g select new linq在資料分組時,不會像資料庫group by那樣,表面上只返回group by後的一條資料,而是根據要分組的條件,把資料匯聚成乙個字典,字典的鍵為...

LINQ優化 將GroupBy換做Distinct

這樣做也是沒有辦法的,我之前專案中,查詢中這樣寫的分組 1 form t in db.table 2where t.state true 3 group t by new 4 9 into p 10select new 導致的就是,資料表中不到1w行資料,經過分組後是752行,但是第一次查詢要將近1...