[英]LINQ to returns count even the list is empty
我在另一個LINQ語句中有這段代碼。
VideoLinks = (from video in m.VideoLinks.DefaultIfEmpty(new VideoGallery())
orderby video.CreatedDate
select new VideoGallery()
{
Source = video.Source,
Type = video.Type,
Links = video.Links,
Title = video.Title
}).ToList()
不幸的是,如果不通過我使用DefaultIfEmpty它是一個例外。 如果我使用DefaultIfEmpty,即使m.VideoLinks為null,我也會為視頻鏈接計數為1。
因此,如果m.VideoLinks為null,那么現在如何避免獲得計數1
DefaultIfEmpty將為您提供一個默認值。 當您在其上調用ToList()時,它計為一項...因此您的計數為1。
看起來您正在使用linq-to-objects,因此您應該添加where video != null
VideoLinks = (from video in m.VideoLinks
where video != null
orderby video.CreatedDate
select new VideoGallery()
{
Source = video.Source,
Type = video.Type,
Links = video.Links,
Title = video.Title
}).ToList()
wllmsaccnt是正確的-您的問題是語句的“ DefaultIfEmpty”部分。 根據定義,您要求根據此方法的定義在集合中至少包含一項:
如果序列為空,則返回指定序列的元素或單例集合中的指定值
我認為這里的重要問題是,不使用DefaultIfEmpty時會收到什么異常? 如果您告訴我們,也許我們可以幫助您避免這種情況...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.