将简单的SQL组by转换为LINQ to SQL
本文关键字:SQL LINQ to 转换 简单 by | 更新日期: 2023-09-27 18:01:20
我遇到麻烦了。我无法理解Stack Overflow上已有的答案,而且我对LINQ to SQL太陌生了,无法自己解决这个问题。
请参阅此SQL:
select p.Name as ProductName, SUM(o.NumberOf) as TotalOrdered from [Order] o
join [Product] p on o.ProductId = p.Id
group by p.Name
返回一个漂亮的两列表,左边是产品名称,右边是已订购的产品总数(所有订单(。如何在LINQ to SQL中复制此项?
到目前为止,我得到的是:
var ctx = new DataClasses1DataContext();
var totalProducts = (from o in ctx.Orders
join p in ctx.Products on o.ProductId equals p.Id
select new { p.Name, o.NumberOf })
.GroupBy(t => t.Name)
.Select(g => g.Key, ... );
什么在?
在我看来,它就像你想要的:
.Select(g => new { ProductName = g.Key, TotalOrdered = g.Sum(x => x.NumberOf) })
您可以将整个查询作为单个查询表达式进行,也可以完全不使用查询表达式:
var totalProducts = ctx.Orders
.Join(ctx.Products, o => o.ProductId, p => p.Id,
(o, p) => new { p.Name, o.NumberOf })
.GroupBy(t => t.Name,
pair => pair.Name, // Key selector
pair => pair.NumberOf, // Element selector
(key, numbers) => new {
ProductName = key,
TotalOrdered = numbers.Sum())
});
或者:
var totalProdcuts = from o in ctx.Orders
join p in ctx.Products on o.ProductId equals p.Id
group o.NumberOf by p.Name into g
select new { ProductName = g.Key, TotalOrdered = g.Sum() };
TotalOrdered = g.Sum(o => o.NumberOf)
利用上面的。。。。则语句可能是
select new { ProductName= g.Key, TotalOrdered = g.Sum(o => o.NumberOf) };
var query = from o in ctx.Orders
join p in ctx.Products on
o.ProductId equals p.Id
group o by new { p.Name, o.NumberOf } into g
select new { ProductName= g.Key, TotalOrdered = g.Sum(o => o.NumberOf) };
只需将其粘贴在此处,以防了解如何通过GroupJoin方法实现这一点很有帮助:
var totalProducts = ctx.Products.GroupJoin(ctx.Orders,
outerKeySelProduct => outerKeySelProduct.Id,
innerKeySelOrder => innerKeySelOrder.ProductId,
(outerKeySelProduct, innerKeySelOrder) => new
{
ProductName = outerKeySelProduct.Name,
TotalOrdered = innerKeySelOrder.Select(n => n.NumberOf).Sum()
});
如果可以改进的话,很高兴能对它进行编辑。