开发者

LINQ to returns count even the list is empty

开发者 https://www.devze.com 2023-04-04 05:08 出处:网络
I have this block of code inside another LINQ statement. VideoLinks = (from video in m.VideoLinks.DefaultIfEmpty(new VideoGallery())

I have this block of code inside another LINQ statement.

 VideoLinks = (from video in m.VideoLinks.DefaultIfEmpty(new VideoGallery())
                                              orderby video.CreatedDate
                                              select new VideoGaller开发者_如何学Pythony()
                                              {
                                                  Source = video.Source,
                                                  Type = video.Type,
                                                  Links = video.Links,
                                                  Title = video.Title
                                              }).ToList()

unfortunately if dont use DefaultIfEmpty its through me an exception. If I use DefaultIfEmpty i give count as 1 for videolinks even if m.VideoLinks is null.

So now how can avoid getting count 1 if m.VideoLinks is null


DefaultIfEmpty is going to give you a default value. It counts as an item when you call ToList() on it...thus your count is 1.


This looks like you are using linq-to-objects, so you should add a 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 is correct - your problem is the "DefaultIfEmpty" portion of your statement. By definition, you are requesting that there be at least one item in the collection, according to the definition of this method:

Returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty

I think the important question here is what exception are you receiving when you don't use DefaultIfEmpty? If you tell us that, perhaps we can help you avoid it...

0

精彩评论

暂无评论...
验证码 换一张
取 消