Linq query with nullable sum

前端 未结 14 1897
粉色の甜心
粉色の甜心 2020-11-29 06:23
from i in Db.Items
select new VotedItem
{
    ItemId = i.ItemId,
    Points = (from v in Db.Votes
              where b.ItemId == v.ItemId
              select v.Poi         


        
14条回答
  •  爱一瞬间的悲伤
    2020-11-29 06:40

    Similar to previous answers, but you can also cast the result of the entire sum to the nullable type.

    from i in Db.Items
    select new VotedItem
    {
        ItemId = i.ItemId,
        Points = (decimal?)((from v in Db.Votes
                  where b.ItemId == v.ItemId
                  select v.Points).Sum()) ?? 0
    }
    

    Arguably this better fits what is really going on but it has the same effect as the cast in this answer.

提交回复
热议问题