Linq:int之和 [英] Linq: Sum of int

查看:67
本文介绍了Linq:int之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到"不能将空值分配给类型为System.Int32的成员,这是非空值类型",当我执行空语句的Sum()时. ResultView可以正常工作,但是可以

I am getting "The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type" When executing Sum() of my empty statement. ResultView works fine, but either

var r = from v in DataContext.Visits
        join bs in DataContext.BaseContents on v.BaseContentID equals bs.Id
        where (bs.CreatedBy == userId) && (v.DateVisited.Year == workDate.Year) &&
        (v.DateVisited.Month == workDate.Month) && (v.DateVisited.Day == workDate.Day) &&
        (v.IsPreviewed == false) && (bs.ProfileProjectId != null)
        select v;

int? number = r.Sum( v => v.Counter);

两个

var r = from v in DataContext.Visits
        join bs in DataContext.BaseContents on v.BaseContentID equals bs.Id
        where (bs.CreatedBy == userId) && (v.DateVisited.Year == workDate.Year) &&
        (v.DateVisited.Month == workDate.Month) && (v.DateVisited.Day == workDate.Day) &&
        (v.IsPreviewed == false) && (bs.ProfileProjectId != null)
        select v.Counter;

int? number = r.Sum(v);

失败,具有相同的例外.

fails with same exception.

推荐答案

尝试一下(已更新):

int number = r.Sum(v => (int?)v.Counter) ?? 0;

这篇关于Linq:int之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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