2015-01-16 127 views
0

我有一個2表,我做了一些連接以基於某些要求返回記錄列表。 我能夠通過查詢爲我的requiremnet和fecth記錄編寫一個組,但我需要Linq查詢中的相同內容。 我的SQL查詢:如何在linq C#中使用group by並獲取記錄列表

select 
    MiscServiceDesc, 
    sum(PaymentAmount), 
    count(PaymentAmount) 
from 
    MiscTransaction MT 
join MiscService MS 
    on MT.MiscServiceID = MS.MiscServiceID 
group by 
    MiscServiceDesc 

其中MiscTransaction和MiscService是我的兩個表。

任何幫助? 在此先感謝

+0

我需要一個加入時。 – Santosh

+0

@Santosh它的寫法是一樣的,加入或不加入。 – Magnus

+0

也檢查此帖:http://stackoverflow.com/questions/27730575/linq-to-sql-left-outer-join-with-group-by-and-having-clause –

回答

2

試試這個。我不知道MiscServiceDesc,PaymentAmount,PaymentAmount這些列中的哪些列在MiscTransaction表或MiscService表中,但是如果需要,您可以適當地更改代碼。

var result = (from mt in MiscTransaction 
       join ms in MiscService on mt.MiscServiceID equals ms.MiscServiceID 
       select new {ms.MiscServiceDesc, mt.PaymentAmount} into lst 
       group lst by lst.MiscServiceDesc into gr 
       select new {MiscServiceDesc = gr.Key, Summ = gr.Sum(c=>c.PaymentAmount), Count = gr.Count()} 
     ).ToList(); 
相關問題