I have a TSQL statement with GROUP BY. I want to know the equivalent LINQ and lambda expression of this in C#.
SELECT ProductId, SUM(QTY)
From Test
Group BY ProductId
Order BY SUM(QTY) DESC
The LINQ equivalent query will be:
var resultsLinq = from test in tests
group new { test.QTY } by test.ProductId into prdGroup
let qtySum = prdGroup.Sum(t => t.QTY)
orderby qtySum descending
select new { ProdyctId = prdGroup.Key, QtySum = qtySum };
and the lambda equivalent query will be:
var resultsLamda = tests
.GroupBy(test => test.ProductId)
.Select(prdGroup => new { ProdyctId = prdGroup.Key, QtySum = prdGroup.Sum(t => t.QTY) })
.OrderByDescending(prdGroup => prdGroup.QtySum);
The full code sample:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp1
{
class Test
{
public int ProductId { get; set; }
public int QTY { get; set; }
}
class Program
{
static void Main()
{
IList<Test> tests = new List<Test>
{
new Test { ProductId = 1, QTY = 10 },
new Test { ProductId = 1, QTY = 20 },
new Test { ProductId = 1, QTY = 30 },
new Test { ProductId = 2, QTY = 40 },
new Test { ProductId = 2, QTY = 50 }
};
var resultsLinq = from test in tests
group new { test.QTY } by test.ProductId into prdGroup
let qtySum = prdGroup.Sum(t => t.QTY)
orderby qtySum descending
select new { ProdyctId = prdGroup.Key, QtySum = qtySum };
var resultsLamda = tests
.GroupBy(test => test.ProductId)
.Select(prdGroup => new { ProdyctId = prdGroup.Key, QtySum = prdGroup.Sum(t => t.QTY) })
.OrderByDescending(prdGroup => prdGroup.QtySum);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.