LINQ基于最新日期的条目总数 [英] LINQ Sum of entries based on latest date

查看:36
本文介绍了LINQ基于最新日期的条目总数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张像这样的桌子:

I have a table like so:

Code | BuildDate  | BuildQuantity
---------------------------------
1    | 2013-04-10 | 4
1    | 2014-09-23 | 1
1    | 2014-08-20 | 2
7    | 2014-02-05 | 4

我希望LINQ查询为每个代码选择最新的构建日期,为该代码选择BuildQuantity,以此类推,对所有记录进行汇总.因此,对于上述数据,结果应为 1 + 4 = 5 .

I want the LINQ query to pick up the LATEST Build date for each Code, pick the BuildQuantity for that Code, and so on for all the records, and sum it up. So for the data above, the result should be 1 + 4 = 5.

这就是我要尝试的:

var built = (from tb in db.Builds
             orderby tb.BuildDate descending
             group tb by tb.Code into tbgrp
             select tbgrp.Sum(c => c.BuildQuantity)).First();

此查询返回7 ...我在做什么错了?

This query returns 7... What am I doing wrong?

推荐答案

在获取第一个代码之前,您要对所有代码的BuildQuantities求和,而不是要对第一个代码求和.

You are summing all code's BuildQuantities before you take the first, instead you want to sum the firsts.

int built = db.Builds
    .GroupBy(b => b.Code)
    .Sum(g => g.OrderByDescending(b => b.BuildDate).First().BuildQuantity); 

这篇关于LINQ基于最新日期的条目总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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