Thursday, November 12, 2009

Multiple columns Group by option with LINQ

Group by clause is very common while writing T-SQL queries. How can we do the same in LINQ using c# and EDMX files.

Here is the code snippet for your reference wherein InvoiceNo, InvoiceRowNo are the two group by columns.

// Step 4: Extract amount paid for each InvoiceNo,InvoiceRowNo

var querymoneyFinal = from ml in moneyList
group ml by new { ml.InvoiceNo, ml.InvoiceRowNo } into g
select new MatchedPaymentForStockReportDTO
{
InvoiceNo = g.Key.InvoiceNo,
InvoiceRowNo = g.Key.InvoiceRowNo,
Amount = g.Sum(w => w.Amount)
};
List MoneyFinalList = querymoneyFinal.ToList();

the equivalent T-SQL code will be some thing like the following:
Select
InvoiceNo,InvoiceRowNo, sum(Amount)
from
moneyList group by InvoiceNo,InvoiceRowNo;

Hope you enjoy it !!

Bye Bye come up with more code snippets.

No comments:

Post a Comment