在LINQ中返回多个聚合列 [英] Return multiple aggregate columns in LINQ
本文介绍了在LINQ中返回多个聚合列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将以下SQL转换为LINQ:
I would like to translate the following SQL into LINQ:
SELECT
(Select count(BidID)) as TotalBidNum,
(Select sum(Amount)) as TotalBidVal
FROM Bids
我已经尝试过了:
from b in _dataContext.Bids
select new { TotalBidVal = b.Sum(p => p.Amount), TotalBidNum = b.Count(p => p.BidId) }
但收到错误消息出价不包含和"的定义,并且找不到扩展方法和"接受第一个出价"类型的参数.
but get an error "Bids does not contain a definition for "Sum" and no extension method "Sum" accepting a first argument of type "Bids" could be found.
如何在LINQ中做到这一点?
How can I do this in LINQ?
谢谢
结论:
最终答案是:
var ctx = _dataContext.Bids;
var itemsBid = (from b in _dataContext.Bids
select new { TotalBidVal = ctx.Sum(p => p.Amount), TotalBidNum = ctx.Count() }).First();
推荐答案
您可以尝试一下.变量b是一个实体(对于每次迭代),而ctx是一个实体集,具有所需的扩展方法.
You could try this out. The variable b is an entity (for every iteration) while ctx is an entityset which has the extension methods you need.
var ctx = _dataContext.Bids;
var result = ctx
.Select( x => new
{
TotalBidVal = ctx.Sum ( p => p.Amount ),
TotalBidNum = ctx.Count( p => p.BidId )
} )
.First();
这篇关于在LINQ中返回多个聚合列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文