本文介紹了總和可為空的 Linq 查詢的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
from i in Db.Items
select new VotedItem
{
ItemId = i.ItemId,
Points = (from v in Db.Votes
where b.ItemId == v.ItemId
select v.Points).Sum()
}
我收到了這個查詢,但是如果沒有發(fā)現(xiàn)異常投票,它就會失敗:
I got this query, however it fails if no votes are found with exception:
The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.
我假設它是因為 sum 返回一個 int 而不是一個可為空的 int,所以給 sum 一個 int?由于輸入只給出相同的錯誤,可能導致 sum 僅適用于整數(shù).
I assume its because sum returns an int and not a nullable int, giving sum a int? as input only give the same error, probably cause sum only workes on ints.
有什么好的解決方法嗎?
Any good workaround for this?
推薦答案
from i in Db.Items
select new VotedItem
{
ItemId = i.ItemId,
Points = (from v in Db.Votes
where b.ItemId == v.ItemId
select v.Points ?? 0).Sum()
}
編輯 - 好吧,這個怎么樣...(再次拍攝,因為我不知道你的型號...):
EDIT - ok what about this... (Shooting again since I don't know your model...):
from i in Db.Items
select new VotedItem
{
ItemId = i.ItemId,
Points = (from v in Db.Votes
where b.ItemId == v.ItemId)
.Sum(v => v.Points)
}
這篇關于總和可為空的 Linq 查詢的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯(lián)系我們刪除處理,感謝您的支持!