c# - Linq 求和和 null

标签 c# asp.net linq sum

我有一个问题:

var qq = (from c in db.tblArcadeGames
        where
            c.IsDeleted == false &&
            c.ParentGameID == 0 &&
            c.Approved == true
        let aggPlays = c.Plays + db.tblArcadeGames.Where(v => v.ParentGameID == c.ID).Sum(v => (int?)v.Plays)
        orderby aggPlays descending
        select new { c, aggPlays })
        .Skip(Skip)
        .Take(Fetch);

foreach (var g in qq)
{
    HttpContext.Current.Response.Write("{" + g.aggPlays + "}\n");
}

当我在上面的循环中打印出 aggPlays 时,它们显示为:

{21}
{}
{}
{}

问题似乎是,如果不存在记录,Sum() 将返回 null。我不确定如何解决这个问题,这样 c.Plays + null 就不会等于 null 而只是 c.Plays

最佳答案

您可以通过不返回 int? 来更正此问题,而是直接转换为 int:

.Sum(v => v.Plays ?? 0)

关于c# - Linq 求和和 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8663479/

相关文章:

c# - 如何将文件从 UNC 共享复制到本地系统?

c# - winforms设计器中自定义控件的格式属性

c# - 我们如何优化 gridview 中的记录?

c# - 不支持异常 : LINQ to Entities does not recognize the method

c# - C# 中的 List.Orderby 首先排序为偶数升序的数字,然后为奇数降序的相同数字

c# - 如何编写 LINQ 左连接

c# - 使用 winforms 给 excel 单元格上色

c# - 启动 RoboCode 时出错

asp.net - ASP.NET 如何生成 HTML5 代码?

c# - 在 VS2010 中为具有多个项目的解决方案创建部署包