在 LINQ 中返回多个聚合列 [英] Return multiple aggregate columns in LINQ

查看:11
本文介绍了在 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) }

但收到错误Bids 不包含Sum"的定义,并且找不到接受Bids"类型的第一个参数的扩展方法Sum".

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆