C# 在Linq中求和2列
我试图对LINQ中的两列进行求和。以下是我的LINQ声明C# 在Linq中求和2列,c#,asp.net-mvc,linq,C#,Asp.net Mvc,Linq,我试图对LINQ中的两列进行求和。以下是我的LINQ声明 var SigmaGood = from n in db.tbl_dppITHr where n.ProductionHour >= SelectedDateDayShiftStart where n.ProductionHour <= SelectedDateEnd select n.part1 + n.part2 Vi
var SigmaGood = from n in db.tbl_dppITHr
where n.ProductionHour >= SelectedDateDayShiftStart
where n.ProductionHour <= SelectedDateEnd
select n.part1 + n.part2
ViewData["GoodTotal"] = SigmaGood.Sum();
var SigmaGood=从n开始,单位为db.tbl\u dppITHr
其中n.ProductionHour>=SelectedDateDayShiftsStart
其中n.ProductionHour您确定part1
和part2
有价值吗
var SigmaGood = from n in db.tbl_dppITHr
where n.ProductionHour >= SelectedDateDayShiftStart
where n.ProductionHour <= SelectedDateEnd
select n.part1 ?? 0 + n.part2 ?? 0
ViewData["GoodTotal"] = SigmaGood.Sum();
var SigmaGood=从n开始,单位为db.tbl\u dppITHr
其中n.ProductionHour>=SelectedDateDayShiftsStart
其中n.ProductionHour尝试以下方法:
var sum = db.tbl_dppITHr.Where(n => n.ProductionHour >= SelectedDateDayShiftStart
&& n.ProductionHour <= SelectedDateEnd)
.Sum(n => n.part1 + n.part2);
var sum=db.tbl\dppITHr.Where(n=>n.ProductionHour>=selectedDateDayShiftsStart
&&n.生产时间n.部件1+n.部件2);
我想说,空白必须意味着存储值的键与读取/显示的键不匹配。如果有,您至少会看到0
,而不是空白
分两步完成并调试
var total = sigmaGood.Sum();
ViewData["GoodTotal"] = total; //breakpoint on this line and check value of total.
或者硬编码一个测试值,我打赌它仍然是空的:
ViewData["GoodTotal"] = 1234;
您确定输入数据中没有null
?这可能会被呈现为SQLSUM()
,如果任何输入值为null
,SUM
的结果总是一个数字,即使没有元素求和,也不可能得到“空白”。请指定您实际得到的。什么是空白?如果列是数字列,则无法获得空白。这就是为什么我认为它们从ViewData
@DanielHilgarthQueryable读取的键不同。Sum
很可能返回null
@Yosi有正确的答案,但删除了。@Magnus:啊,实施细节的乐趣。我必须承认,我完全忽略了这样一个事实:OP可能不使用Enumerable.Sum
,而是使用Queryable.Sum
。谢谢你指出这一点。这其实有点尴尬…:-)它不会编译,当您修复编译错误时,它与OPNow的代码没有什么不同,OPNow会编译。我知道,我不是回答者,所以我只是纠正了一些小错误,没有改变答案answer@CarlosMu尼奥斯:你在自言自语吗?;-)@丹尼尔·希尔加思。不,我是在回答你的评论,这不会改变结果。即使它们的值不为null,求和的结果也将是0
,而不是“空白”。@DanielHilgarth-如果一个值为null
,另一个值为7
?7
,则结果不包括null值当我这么做的时候,总数等于Null@Inkey当前位置正如我在对问题的评论中所说,这是不可能的。请显示一个屏幕截图。@Inkey:执行该行后,您需要检查total
的值。换句话说,将断点放在当前打开的断点之后的一行上,然后再次检查。@weston:因为实际签名是T Sum(IEnumerable)
,因此无法在签名中打开可为null的值。没有Sum(IEnumerable)这样的东西。此外,这可能是在查询IQueryable。是100%,如果为null,则数据库中的值将为空0@Inkey:DECLARE@i int=NULL;在SQL Server 2008 R2中选择SUM(@i)
返回NULL
。