Return multiple aggregate columns in LINQ

前端 未结 4 1274
孤城傲影
孤城傲影 2020-12-06 11:25

I would like to translate the following SQL into LINQ:

SELECT
    (Select count(BidID)) as TotalBidNum,
    (Select sum(Amount)) as TotalBidVal
FROM Bids


        
相关标签:
4条回答
  • 2020-12-06 11:57

    here's an alternative to scartag's solution:

    (from b in _dataContext.Bids.Take(1)
    select new 
    {
        TotalBidVal = _dataContext.Bids.Sum(p => p.Amount), 
        TotalBidNum = _dataContext.Bids.Count()
    }).Single();
    

    Although there's no real reason you can't just say:

    var result = new 
    {
        TotalBidVal = _dataContext.Bids.Sum(p => p.Amount), 
        TotalBidNum = _dataContext.Bids.Count()
    };
    

    It hits the database twice, but its very readable

    0 讨论(0)
  • 2020-12-06 11:58

    You can write this query using GroupBy. The Lambda expression is as follows:

        var itemsBid = db.Bids
                         .GroupBy( i => 1)
                         .Select( g => new
                         {
                              TotalBidVal = g.Sum(item => item.Amount), 
                              TotalBidNum = g.Count(item => item.BidId)
                         });
    
    0 讨论(0)
  • 2020-12-06 12:05

    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();
    
    0 讨论(0)
  • 2020-12-06 12:10

    You could do it using the Aggregate Clause.

    Aggregate t In _dataContext.Bids
    Into TotalBidNum = Count(BidID),
         TotalBidVal = Sum(Amount)
    

    If you're using Fx4+ or an extension dll for Fx2, you could also benfit from parallelism by using

    Aggregate t In _dataContext.Bids.AsParallel
    
    0 讨论(0)
提交回复
热议问题