在 LINQ 中返回多个聚合列
我想将以下 SQL 转换为 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) }
但收到错误“Bids 不包含“Sum”的定义,并且没有扩展方法“Sum”接受类型为“Bids”的第一个参数 我怎样
才能在 LINQ 中做到这一点?
结论
:
最终答案是:
var ctx = _dataContext.Bids;
var itemsBid = (from b in _dataContext.Bids
select new { TotalBidVal = ctx.Sum(p => p.Amount), TotalBidNum = ctx.Count() }).First();
I would like to translate the following SQL into LINQ:
SELECT
(Select count(BidID)) as TotalBidNum,
(Select sum(Amount)) as TotalBidVal
FROM Bids
I've tried this:
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.
How can I do this in LINQ?
Thanks
CONCLUDING:
The final answer was:
var ctx = _dataContext.Bids;
var itemsBid = (from b in _dataContext.Bids
select new { TotalBidVal = ctx.Sum(p => p.Amount), TotalBidNum = ctx.Count() }).First();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
GroupBy
编写此查询。 Lambda表达式如下:You can write this query using
GroupBy
. The Lambda expression is as follows:你可以试试这个。变量 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.
这是斯卡塔格解决方案的替代方案:
虽然没有真正的理由你不能只是说:
它访问了数据库两次,但它的可读性非常好
here's an alternative to scartag's solution:
Although there's no real reason you can't just say:
It hits the database twice, but its very readable
您可以使用 聚合子句来完成此操作。
如果您使用的是 Fx4+ 或 Fx2 的扩展 dll,您还可以通过使用并行性来受益
You could do it using the Aggregate Clause.
If you're using Fx4+ or an extension dll for Fx2, you could also benfit from parallelism by using